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 re
It's O(N)
:
int sum = 0;
int M = 0; // This is the output
foreach (int n in input) {
sum += n;
if (sum > M)
M = sum;
if (sum < 0)
sum = 0;
}
The idea is to keep the sum of all integers that have been encountered since last reset. A reset occurs when the sum goes below zero - i.e. there are too many negative numbers in the current interval to make it possibly the best one.
I have tried and tested this. In case all numbers are negative, it returns the greatest negative number.
Test cases:
{-5, -1, -2, -3, -4}
{ 12, 14, 0, -4, 61, -39}
{2, -8, 3, -2, 4, -10}
Code:
public int FindLargestSum(int[] arr)
{
int max = Integer.MIN_VALUE;
int sum = 0;
for(int i=0; i < arr.length; i++)
{
if(arr[i] > max) max = arr[i];
sum += arr[i];
if(sum < 0)
sum = 0;
else if(sum > max)
max = sum;
}
return max;
}
This is a classical, well known, problem that is an excellent eye-opener in any algorithm course. It is hard to find a better/simpler starter. You can find an n*3-, n*2-, nlogn- and even the simple n-algorithm.
I found the problem discussed/solved in John Bentley´s "Programming Pearls" from 1986 - and did use it for years as a starter in our Algorithm Course at NTNU/Trondheim. Some 20 years ago I first used it in an examination for about 250 students, where just 1 student did discover all the 4 solutions, see above. He, Bjørn Olstad, became the "youngest professor ever" at NTNU in Trondheim, and has still this status beside heading the MSFT search division in Oslo. Bjørn also took the challenge to find good practical applications of the algorithm. Do you see some?