R
E
A
C
T
O

xamples
epeat
ode
pproach
ptimize
est
{Maximum Subarray Problem}

The Question
Given an array of integers, find a contiguous subarray that sums to the greatest value.
For Example:
var array = [−2, 1, −3, 4, −1, 2, 1, −5, 4];
The greatest subarray is [4,-1,2,1] and its sum is 6.
This question can be solved in O(n^2) time if you check all possible subarrays, but there exists a way to solve it in linear time: O(n).

Breakdown
1. O(n) means only 1 for loop
2. Break down the problem into smaller parts
3. As you move in the for-loop, what are the rules that determine if the array is a possible subarray.
4. You can assume that if the array is all negative numbers, you would return 0, or an empty array.

1. Rules to recognize
var array = [−2, 1, −3, 4, −1, 2, 1, −5, 4];
// Ends of the subarray must be positive, or else you could chop either end off and get a higher total
// Because you are trying to do this in one for loop,
//you will try and work to find the subarray while moving left to right
function maxSubArray(arr){
var sum = 0;
for (var i = 0; i < arr.length; i++){
}
}
// The key is to realize that if a sum is negative at any point,
//you may as well start at the next positive number.

2. finding max sum first
var array = [−2, 1, −3, 4, −1, 2, 1, −5, 4];
//The sum is what will tell you
//that the array is the one you want
function maxSub(array){
var curr = 0, prev = 0;
for (var i=0; i < array.length; i++){
prev = Math.max(0, prev+array[i]);
curr = Math.max(curr, prev);
}
return curr;
}

3. Now let's make it return an array
var array = [−2, 1, −3, 4, −1, 2, 1, −5, 4];
function maxSub(array){
var curr = 0, prev = 0;
var start=0, end=0;
var maxStart,maxEnd;
for (var i=0; i < array.length; i++){
if (0 >= prev+array[i]){
prev = 0;
start = i+1;
end = i+1;
} else {
prev = prev + array[i];
end = i+1;
}
if (prev > curr){
maxStart = start;
maxEnd = end;
curr = prev;
}
}
return array.slice(maxStart,maxEnd);
}
console.log(maxSub(array));

Conclusion
Can draw a table of values to help you keep track of what the sum values are at every step.
Up to the interviewer on how to handle edge cases, for example handling subarrays of equal value.
Can test in repl.it
Don't google it right away.
Reacto: Maximum Subarray
By Justin Sung
Reacto: Maximum Subarray
- 945