您的位置:首页 > 其它

【LeetCode】Maximum Subarray 解题报告

2017-05-02 20:10 453 查看

【LeetCode】Maximum Subarray 解题报告

标签(空格分隔): LeetCode

题目地址:https://leetcode.com/problems/maximum-subarray/#/description

题目描述:

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [-2,1,-3,4,-1,2,1,-5,4],

the contiguous subarray [4,-1,2,1] has the largest sum = 6.

Ways

明显的DP方法去解决。DP比较简单的方法就是通过构建一个和原长一样长的数组,在dp数组中,每个位置的数字等于当前数字加上前面个位置的dp,当前面的位置是负数时就不要加了,如果加上会使当前位置的dp变小。用max值保留最大的dp数组中的值。

public class Solution {
public int maxSubArray(int[] nums) {
int len = nums.length;
int[] dp = new int[len];
dp[0] = nums[0];
int max = dp[0];
for(int i = 1; i < len; i++){
dp[i] = nums[i] + (dp[i -1] > 0 ? dp[i -1] : 0);
max = Math.max(max, dp[i]);
}
return max;
}
}


Date

2017 年 5 月 2 日
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: