Description:
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.
Solution:
这道题的要求是寻找连续和最大的子字符串
既然要寻找最大的和,那么我们必须从头到尾遍历数组。
首先假定连续和最大的子字符串的开始位置在0处,并定义一个变量temp存储当前连续子串的和,变量res存储最终的结果。
向后遍历,比较当前值与相加和的大小,
如果当前值大于相加和,则将连续字符串的开头移至当前值处,新的相加和也变为当前值;
如果当前值小于相加和,则将其加入相加和中。
每次遍历时,都将当前值与res相比,取其中大的赋值给res。
等到遍历完成后,输出结果即得到答案。
Code:
public int maxSubArray(int[] nums) {
int res = Integer.MIN_VALUE;
int temp = 0;
for (int num : nums){
temp = Math.max(temp+num, num);
res = Math.max(temp, res);
}
return res;
}
顺便写一下提交情况:
摘录几个其他的答案以后优化的时候看:
public int maxSubArray(int[] A) {
int n = A.length;
int[] dp = new int[n];//dp[i] means the maximum subarray ending with A[i];
dp[0] = A[0];
int max = dp[0];
for(int i = 1; i < n; i++){
dp[i] = A[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0);
max = Math.max(max, dp[i]);
}
return max;
}
这道题还要求使用 divide and conquer approach来解题,但是方法看起来太麻烦了我现在懒得做,等我下次复习的时候再做 =口=