• + 0 comments

    C#

    public static List<int> maxSubarray(List<int> arr)
    {
        if (arr.Count == 1)
        {
            return new List<int>() { arr[0], arr[0] };
        }
    
        var result = new List<int>();
    
        var isAllNegative = arr[0] < 0;
        var positiveSum = Math.Max(0, arr[0]);
        var minNegative = arr[0] < 0 ? arr[0] : -1 * int.MaxValue;
    
        var currentSubarrayMax = arr[0];
        var maxSoFar = arr[0];
    
        for (int i = 1; i < arr.Count; ++i)
        {
            // maximum subsequence sum
            if (arr[i] >= 0)
            {
                positiveSum += arr[i];
    
                if (isAllNegative)
                {
                    isAllNegative = false;
                }
            }
    
            if (isAllNegative)
            {
                minNegative = Math.Max(minNegative, arr[i]);
            }
    
            // maximum subarray sum
            currentSubarrayMax = Math.Max(arr[i], currentSubarrayMax + arr[i]);
            maxSoFar = Math.Max(maxSoFar, currentSubarrayMax);
        }
    
        result.Add(maxSoFar);
        result.Add(isAllNegative ? minNegative : positiveSum);
    
        return result;
    }