Given an integer array nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
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.
Tip:经典的最大子列和问题,在follow up中提到建议使用分治法,这里我们使用动态规划(dynamic programming)来处理这个问题
Current best = Max(preBest+now,now);
public class MaximumSubarraySolution {
public int maxSubArray(int[] nums) {
int result = nums[0];
int currentBest = nums[0];
int len = nums.length;
for (int i = 1; i < len; i++) {
currentBest = Math.max(nums[i], currentBest + nums[i]);//计算当前位置最大子列和
result = Math.max(currentBest, result);//选取最大的子列和
}
return result;
}
}