Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Largest sum contiguous subarray (Interview Question) [duplicate]

Possible Duplicate:
Find the maximum interval sum in a list of real numbers.

I was asked the following question today at Adobe interview for the position of software engineer.

Problem Given a array arr[1..n] of integers. Write an algorithm to find the sum of contiguous subarray within the array which has the largest sum. Return 0 if all the numbers are negative.

Example

Given array arr[1..6] = [ 12, 14, 0, -4, 61, -39 ]

Answer

83 constructed with [ 12, 14, 0, -4, 61 ].

I could come up with a solution running in O(n logn) but I don't think it was very efficient. The interviewer asked to me to write an O(n) algorithm. I couldn't come up with it.

Any idea about how to write an O(n) solution for this problem? Algorithm to be implemented either in C/C++/Java.

Thanks in advance

like image 285
WebDev Avatar asked Mar 21 '11 13:03

WebDev


People also ask

How do you find the largest sum of the contiguous Subarray?

Simple Approach: Run a loop for i from 0 to n – 1, where n is the size of the array. Now, we will run a nested loop for j from i to n – 1 and add the value of the element at index j to a variable currentMax. Lastly, for every subarray, we will check if the currentMax is the maximum sum of all contiguous subarrays.

Is kadane's algorithm hard?

Don't be afraid this is not very difficult.... For new programmer, this is very essential... We know a little bit for that we don't answer many problem as like "largest sum contiguous sub array" that's really very easy to determine largest sum if we know the following algorithm.....

What is a best possible solution for maximum product Subarray problem?

The maximum product subarray is the product of all the integers if the array only contains positive numbers. The most effective way to solve the problem is through dynamic programming .

Is kadane's algorithm DP?

Kadane's algorithm is usually implemented using a bottom up DP approach to take advantage of the overlapping subproblems and to only compute each subproblem once, hence turning it to O(n).


1 Answers

You can use Kadane's algorithm which runs in O(n).

Here is the algorithm (shamelessly copied from here)

Initialize:
    max_so_far = 0
    max_ending_here = 0

Loop for each element of the array
  (a) max_ending_here = max_ending_here + a[i]
  (b) if(max_ending_here < 0)
            max_ending_here = 0
  (c) if(max_so_far < max_ending_here)
            max_so_far = max_ending_here
return max_so_far
like image 92
Prasoon Saurav Avatar answered Oct 06 '22 00:10

Prasoon Saurav