Skip to content

Instantly share code, notes, and snippets.

@juanfal
Last active November 14, 2023 18:37
Show Gist options
  • Save juanfal/e2735a69938475585381b70ff6bf3a1e to your computer and use it in GitHub Desktop.
Save juanfal/e2735a69938475585381b70ff6bf3a1e to your computer and use it in GitHub Desktop.
sum of 2 biggest in an array
// t9e14.sum2biggest.cpp
// juanfc 2023-11-14
// https://gist.github.com/juanfal/e2735a69938475585381b70ff6bf3a1e
#include <iostream>
#include <array>
using namespace std;
const int N = 5;
typedef array<int,N> TVec;
int sum2Biggest(TVec a);
int main()
{
cout << sum2Biggest((TVec){{1,2,3,4,5}}) << endl; // 9
cout << sum2Biggest((TVec){{1,5,3,4,5}}) << endl; // 10
return 0;
}
int sum2Biggest(TVec a)
{
int m1, m2;
m1 = m2 = a[0];
for (int i = 1; i < N; ++i) {
if (a[i] > m1) {
m2 = m1;
m1 = a[i];
} else if (a[i] > m2) {
m2 = a[i];
}
}
return m1 + m2;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment