Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the maximum interval sum in a list of real numbers

Here's an interview questions that a colleague asked for a programming position. I thought this was great for watching the interviewee think it through. I'd love to get responses for how the SO community thinks of it.

Given a list of real numbers of length N, say [a_1, a_2, ..., a_N], what is the complexity of finding the maximum value M for which there exist indices 1 <= i <= j <= N such that

a_i + a_{i+1} + ... + a_j = M?

My apologies if this is a classic CS problem.

like image 284
PengOne Avatar asked Mar 16 '11 19:03

PengOne


People also ask

How do you calculate the maximum sub array of a list of numbers?

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.

How do you find the maximum sum of a Subarray?

The idea is simple, find the maximum sum starting from mid point and ending at some point on left of mid, then find the maximum sum starting from mid + 1 and ending with some point on right of mid + 1. Finally, combine the two and return the maximum among left, right and combination of both.

What is kadane's algorithm?

What is Kadane's Algorithm? Kadane's algorithm is an iterative dynamic programming algorithm in which we search for a maximum sum contiguous subarray within a one-dimensional numeric array.


1 Answers

The complexity is just O(n) for Kadane's algorithm:

The algorithm keeps track of the tentative maximum subsequence in (maxSum, maxStartIndex, maxEndIndex). It accumulates a partial sum in currentMaxSum and updates the optimal range when this partial sum becomes larger than maxSum.

like image 189
atp Avatar answered Oct 11 '22 21:10

atp