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){// Write your code hereintmaxSubarraySum=Integer.MIN_VALUE;intcurrent=0;intmaxSubsequenceSum=0;List<Integer>results=newArrayList<>();for(Integeri:arr){current=Math.max(i,current+i);maxSubarraySum=Math.max(maxSubarraySum,current);}List<Integer>positiveElements=newArrayList<>();List<Integer>zeroElements=newArrayList<>();List<Integer>negativeElements=newArrayList<>();for(Integeri:arr){if(i>0){positiveElements.add(i);}if(i==0){zeroElements.add(i);}if(i<0){negativeElements.add(i);}}if(positiveElements.size()!=0){for(Integeri:positiveElements){maxSubsequenceSum+=i;}}elseif(zeroElements.size()!=0){maxSubsequenceSum=0;}else{maxSubsequenceSum=Collections.max(negativeElements);}results.add(maxSubarraySum);results.add(maxSubsequenceSum);returnresults;}
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 →