题目描述:
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
.
分析:
题意:给定一个整型数组,返回它的最大连续子数组和。
思路:这是一道经典的动态规划题。假设数组大小为n,构造数组dp[n],其中dp[i]表示nums[0→i]的最大连续子数组和。初始化dp[0] = nums[0],那么状态转移方程为:dp[i] = dp[i - 1] <= 0? nums[i]: dp[i - 1] + nums[i]。
最后遍历一遍dp[n]找到最大值,返回结果。
时间复杂度为O(n)。
代码:
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int n = nums.size();
// Exceptional Case:
if(n == 0){
return 0;
}
// create and init
int *dp = new int[n];
dp[0] = nums[0];
for(int i = 1; i <= n - 1; i++){
dp[i] = dp[i - 1] <= 0? nums[i]: dp[i - 1] + nums[i];
}
// get answer
int ans = INT_MIN;
for(int i = 0; i <= n - 1; i++){
ans = max(ans, dp[i]);
}
return ans;
}
};