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;
    }
}  
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容