Allstate interview question

Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, given the array [−2,1,−3,4,−1,2,1,−5,4], the contiguous subarray [4,−1,2,1] has the largest sum = 6.

Interview Answers

Anonymous

24 Jul 2016

public class Solution { public int maxSubArray(int[] A) { int max = A[0]; int[] sum = new int[A.length]; sum[0] = A[0]; for (int i = 1; i < A.length; i++) { sum[i] = Math.max(A[i], sum[i - 1] + A[i]); max = Math.max(max, sum[i]); } return max; } }

Anonymous

14 Aug 2018

function max(arr){ let currentMax = null; let currentSection = null; for (let idx = 0; idx a+b, 0); if(newMax > currentMax) { currentMax = newMax; currentSection = newSection; } } } return currentSection; }

Anonymous

22 Aug 2018

function max(arr){ let currentMax = null; let currentSection = null; for (let idxA = 0; idxA a+b); if (newMax > currentMax) { currentSection = newSection; currentMax = newMax; } } } return currentSection; }