首页 > 学院 > 开发设计 > 正文

【LeetCode】53. Maximum Subarray

2019-11-06 06:08:43
字体:
来源:转载
供稿:网友

题目描述

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.

解题思路

动态规划。 对于从0到i,要使得当前的状态取值最大,那么,对于前一个状态的最大值,考虑如下两种情况:

当前一个状态的最大值为负数时,直接抛弃当前一个状态的最大值非负时,那么加上它

也就是说,有如下的状态转移方程:

maxSubArray(A, i) = A[i] + (maxSubArray(A, i - 1) > 0 ? maxSubArray(A, i - 1) : 0)

AC代码

class Solution {public: int maxSubArray(vector<int>& nums) { int n = nums.size(); int *dp = new int[n]; dp[0] = nums[0]; int maxSum = dp[0]; for (int i = 1; i < n; ++i) { dp[i] = nums[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0); maxSum = max(maxSum, dp[i]); } return maxSum; }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表