题目:
https://leetcode-cn.com/problems/maximum-subarray/
思路:
动态规划的思想,dp[i]
表示以i
为结束的数据的最大子数据和。则:
dp[0] = nums[0]
dp[i] = max(dp[i-1] + nums[i], nums[i])
- 最大值即最大的
dp[i]
代码:
class Solution {
public int maxSubArray(int[] nums) {
int res = nums[0];
int mmax = res;
for(int i = 1; i < nums.length; i++){
res = max(res + nums[i], nums[i]);
mmax = max(mmax, res);
}
return mmax;
}
private static int max(int a, int b){
if(a > b){
return a;
} else{
return b;
}
}
}