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.

 

Example 

     input:  [−2, 1, −3, 4, −1, 2, 1, −5, 4]

     expected output: [4,-1,2,1]

 

This subarray ([4,-1,2,1]) is the greatest as it sums to  a sum of 6.

Hint: Time Complexity

 

This can be solved in O(n^2) by checking all possible subarrays (nested loops or recursion).

 

There exists a way to solve it in linear time! O(n)

 Breakdown O(n)

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 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
//   Otherwise, chopping off either end gets a higher total

// To do this in ONE for loop:
//   try to find the subarray while moving left to right


//the basic scaffolding -- a sum and a loop
function maxSubArray(arr){
    var sum = 0;
    
    for (var i = 0; i < arr.length; i++){
        
    }
}



//If a SUM is negative at any point:
//    start checking again 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

//Compare possible sums versus a current max sum

function maxSub(array){
    var maxSum = 0, currSum = 0;
    array.forEach(el => {
        currSum = Math.max(0, currSum + el);
        maxSum = Math.max(maxSum, currSum);
    });
    // return subarray that adds to maxSum
}

3. Now let's make it return an array

function maxSub(array){
    var maxSum = 0, currSum = 0; //hold each sum
    var start = 0, end = 0; //indices of currSum            
    var maxStart = 0, maxEnd = 0; //indices of maxSum
    array.forEach((el, i) => {
    	//if the currSum and the new element are less than 0
    	//   then reset current to start at the next positive sum
        if (currSum + el < 0){
            currSum = 0;
            start = i+1;
            end = i+1;
		//Otherwise, add to the current (sum and end index)
        } else {
            currSum = currSum + el;
            end = i+1;
        }
	    //If the current sum is greater than the current max sum
	    //  then update max (sum and indices)
        if (currSum > maxSum){
            maxStart = start;
            maxEnd = end;
            maxSum = currSum;
        } 
    });
    //return slice -- remember end is exclusive
    return array.slice(maxStart,maxEnd);
}

Big O

If in an interview you can only think of O(n^2) then do that!

 

Talk in your interview!!!

Talk about everything, and when you come to optimizing, talk about potential O(n) solutions and try to implement them, but if you don't that is OK

 

Also, note space complexity as well as time. Our solution has O(6) space complexity, which is constant (O(1)). If your solution has a max SubArray that you push to and return, then you have created a worst case of O(n) space complexity.

Conclusion

Draw a table of values to help you keep track of what the sum values are at every step.


Hold the indices of the max sum to return a slice.


The interviewer can decide how to handle edge cases

(e.g. handling subarrays of equal value.)


Test in repl.it

Made with Slides.com