53. Maximum Subarray.C#

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example:

Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

维护两个变量,globalMax很好理解,关键是localMax,localMax要么等于前面子串的和+遍历到的数字,或者等于当前数字,当等于当前数字时,则local重新开始形成字串。

public class Solution {
    public int MaxSubArray(int[] nums) {
        int length = nums.Length;
        if (length == 0) {
            return 0;
        }
        
        int globalMax = nums[0];
        int localMax = nums[0];
        
        for (int i = 1; i < length; ++i) {
            localMax = Math.Max(nums[i], localMax+nums[i]);    //localMax:前面数之和 或 此数
            globalMax = Math.Max(localMax, globalMax);
        }
        
        return globalMax;
    }
}  

你可能感兴趣的:(53. Maximum Subarray.C#)