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<int>maxSubarray(List<int>arr){if(arr.Count==1){returnnewList<int>(){arr[0],arr[0]};}varresult=newList<int>();varisAllNegative=arr[0]<0;varpositiveSum=Math.Max(0,arr[0]);varminNegative=arr[0]<0?arr[0]:-1*int.MaxValue;varcurrentSubarrayMax=arr[0];varmaxSoFar=arr[0];for(inti=1;i<arr.Count;++i){// maximum subsequence sumif(arr[i]>=0){positiveSum+=arr[i];if(isAllNegative){isAllNegative=false;}}if(isAllNegative){minNegative=Math.Max(minNegative,arr[i]);}// maximum subarray sumcurrentSubarrayMax=Math.Max(arr[i],currentSubarrayMax+arr[i]);maxSoFar=Math.Max(maxSoFar,currentSubarrayMax);}result.Add(maxSoFar);result.Add(isAllNegative?minNegative:positiveSum);returnresult;}
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 →
C#