I am trying to implement the below logic to find the largest sum of vector {5, 9, 7, 11} is sum of elements 9 and 11, which is 20.
Can anyone tell me what is wrong in my code below? Compilation gets terminated here.
In the future, tell us the actual, verbatim compiler error.
Line 26 is not in a function. Also, your indentation is a bit misleading because the closing braces on lines 24 and 27 don't match with the opening brace indentation.
After I remove below line, my code gives output as 32. but expected is 20, given the largest sum of vector {5, 9, 7, 11} is sum of elements 9 and 11, which is 20. How can i change this logic?
Now you're in the fun part! The actual meat of the logic. I don't understand how your current function is finding which two numbers produce the largest sum. Personally, I think you should just start with a fresh version. Tackle it in a different way. Keep track of two variables: One for the largest number found so far, and then another for the second largest number found so far. At the end, you simply add the two largest numbers found (assuming the size of the data >= 2).
Side note, this logic is unnecessarily restricts you:
You don't need this. Just do curr = curr + numbers[i]; If curr is 0, then you'd be adding 0 anyway. [But I don't see how this part helps you accomplish the goal to begin with, so I would just discard it.]
#include <iostream>
usingnamespace std;
int main() {
int arr [4] = {5, 9, 7, 11};
int max = 0;
int len = sizeof(arr)/sizeof(arr[0]);
for (int i=0; i<len-2; i++){
for (int j=i+2; j<len; j++){
if ((arr[i]+arr[j]) > max)
max = arr[i]+arr[j];
}
}
cout << max;
return 0;
}
ok. so what is the optimal solution here considering time complexity?
I am trying to implement findMaxSum method logic that returns the largest sum of any 2 elements in the given vector of positive numbers. For example,
//largest sum of vector {5, 9, 7, 11} is sum of elements 9 and 11, which is 20.
#include <iostream>
#include <algorithm>
usingnamespace std;
int main()
{
int arr[] = {5, 9, 7, 11};
int BIG = arr[0], big = arr[1]; if ( big > BIG ) swap( big, BIG );
int N = sizeof arr / sizeof arr[0];
for ( int i = 2; i < N; i++ ) // O(N) complexity
{
if ( arr[i] > big ) // Something needs changing
{
if ( arr[i] > BIG ) { big = BIG; BIG = arr[i]; } // both need changing
else { big = arr[i]; } // only the smaller needs changing
}
}
cout << "Largest sum of two elements is " << big + BIG << '\n';
}
In a generalized "top n sum" function, sorting I assume is more efficient if n > log2(vec.size()). [And sorting might be better anyway for many datasets due to caching/branch prediction]