Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find max sum of elements in array [duplicate]

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).

like image 387
astoilkov Avatar asked Sep 09 '12 13:09

astoilkov


People also ask

How do you find duplicate elements in an array?

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.


2 Answers

I think Kadane's Algorithm is what you want

like image 92
Qyrus Avatar answered Nov 25 '22 08:11

Qyrus


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;
}
like image 29
Ram G Athreya Avatar answered Nov 25 '22 06:11

Ram G Athreya