声明:本题及相关刷题笔记同步github之中,欢迎Fork & Star GitHub:https://github.com/HoqiheChen。如有不足之处,烦请改正。QQ Mail:851774342@qq.com
Description
Given an integer array nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Brief
最大子序列的值。
Input
[-2,1,-3,4,-1,2,1,-5,4]
Output
6
Explanation
[4,-1,2,1] has the largest sum = 6.
Ideas
动态规划问题。与剑指offer“连续子数组的最大和”同题。
设dp[i]为前i个数字的最大连续子数组的和。
若dp[i-1]的值为负,则dp[i] = nums[i];
否则,为nums[i] 与 dp[i-1]的和。
使用max变量来记录最大值。
所以很容易写出状态转移方程:
d
p
[
i
]
=
n
u
m
s
[
i
−
1
]
+
(
(
d
p
[
i
−
1
]
<
0
)
?
0
:
d
p
[
i
−
1
]
)
;
dp[i] = nums[i - 1] + ((dp[i - 1] < 0) ? 0 : dp[i - 1]);
dp[i]=nums[i−1]+((dp[i−1]<0)?0:dp[i−1]);
Code
class Solution {
public int maxSubArray(int[] nums) {
if(nums.length == 0){
return 0;
}
int[] dp = new int[nums.length + 1];
dp[0] = 0;
dp[1] = nums[0];
int max = dp[1];
for(int i = 2;i < dp.length;i++){
dp[i] = nums[i - 1] + ((dp[i - 1] < 0) ? 0 : dp[i - 1]);
if(dp[i] > max){
max = dp[i];
}
}
return max;
}
}
声明:本题及相关刷题笔记同步github之中,欢迎Fork & Star GitHub:https://github.com/HoqiheChen。如有不足之处,烦请改正。QQ Mail:851774342@qq.com