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;
    }
}  
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容