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.
維護(hù)兩個變量,globalMax很好理解,關(guān)鍵是localMax,localMax要么等于前面子串的和+遍歷到的數(shù)字,或者等于當(dāng)前數(shù)字,當(dāng)?shù)扔诋?dāng)前數(shù)字時,則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:前面數(shù)之和 或 此數(shù)
globalMax = Math.Max(localMax, globalMax);
}
return globalMax;
}
}