We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
publicstaticList<Integer>maxSubarray(List<Integer>arr){intmaxSubarray=Integer.MIN_VALUE;intmaxSubseq=Integer.MIN_VALUE;intcurrentSumSubarray=0,currentSumSubseq=0;for(Integernum:arr){// subarray - Kadane's AlgorithmcurrentSumSubarray+=num;if(currentSumSubarray>maxSubarray)maxSubarray=currentSumSubarray;if(currentSumSubarray<0)currentSumSubarray=0;// subsequenceif(num>=0){// only add if positivecurrentSumSubseq+=num;maxSubseq=currentSumSubseq;}if(num>maxSubseq)// corner case all negativesmaxSubseq=num;}returnnewArrayList<>(Arrays.asList(maxSubarray,maxSubseq));}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
The Maximum Subarray
You are viewing a single comment's thread. Return to all comments →
Don't invent the wheel, use Kadane's Algorithm.