Write a program which by given array of integer values (containing negative integers) finds the maximum sum of successive elements in the array.
Example:
2, 3, -6, -1, 2, -1, 6, 4, -8, 8
Gives
11
I am searching for a solution which is faster than O(N^2).
Duplicate elements can be found using two loops. The outer loop will iterate through the array from 0 to length of the array. The outer loop will select an element. The inner loop will be used to compare the selected element with the rest of the elements of the array.
I think Kadane's Algorithm is what you want
This is actually a textbook problem I studied in college(Data Structures and Algorithms in C by Mark Allen Weiss)...It is a very beautiful and elegant solution and solves in O(N)
int MaxSubsequenceSum(int A[])
{
int sum = 0, maxSum = 0;
for (int j = 0; j < A.Length; j++)
{
sum = sum + A[j];
if (sum > maxSum)
maxSum = sum ;
else if (sum < 0)
sum = 0;
}
return maxSum;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With