We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
输入一个整型数组,数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。
要求时间复杂度为O(n)。
示例1:
输入: nums = [-2,1,-3,4,-1,2,1,-5,4] 输出: 6 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
提示:
解法一(倒数第二个示例超时): 求连续子数组的最大值,根据连续子数组可以联想到前缀和。写了一下,但是倒数第二个示例超时了。。代码如下:
class Solution { public: int maxSubArray(vector<int>& nums) { int n = nums.size(); vector<int> pre(n+1, 0); int res = INT_MIN; for (int i = 1; i < n+1; i++) { pre[i] = pre[i-1] + nums[i-1]; } for (int i = 0; i < n; i++) { for (int j = i+1; j < n+1; j++) { res = max(res, pre[j] - pre[i]); } } return res; } };
解法二: 求最大值,可以用动态规划。 dp[i]表示以nums[i]结尾的连续子数组的和的最大值,状态转移方程为:
dp[0] = nums[0] dp[i] = max(dp[i-1]+nums[i], nums[i]) i > 0
代码如下:
class Solution { public: int maxSubArray(vector<int>& nums) { int n = nums.size(); vector<int> dp(n, 0); int res = nums[0]; dp[0] = nums[0]; for (int i = 1; i < n; i++) { dp[i] = max(dp[i-1]+nums[i], nums[i]); res = max(res, dp[i]); } return res; } };
The text was updated successfully, but these errors were encountered:
No branches or pull requests
输入一个整型数组,数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。
要求时间复杂度为O(n)。
示例1:
提示:
解法一(倒数第二个示例超时):
求连续子数组的最大值,根据连续子数组可以联想到前缀和。写了一下,但是倒数第二个示例超时了。。代码如下:
解法二:
求最大值,可以用动态规划。
dp[i]表示以nums[i]结尾的连续子数组的和的最大值,状态转移方程为:
代码如下:
The text was updated successfully, but these errors were encountered: