LINTCODE——最大子数组III
思路:动态规划的方法,记mustTheLast[i][j]为在前i个数中分成j段,且第j段必须有第i个数的最大值,notTheLast[i][j]为前i个中分成j段,且第j段不一定含有第i个数的最大值;注意初始化的数据,不能全部初始化为0,不然在全部为负整数以及一些其他情况的数组会出错;
动态规划方程为:
mustTheLast[i][j] = max(mustTheLast[i-1][j] + nums[i-1] ,notTheLast[i-1][j-1] + nums[i-1]);
notTheLast[i][j] = max(notTheLast[i-1][j] ,mustTheLast[i][j]);
class Solution {
public:
/*
* @param nums: A list of integers
* @param k: An integer denote to find k non-overlapping subarrays
* @return: An integer denote the sum of max k non-overlapping subarrays
*/
int maxSubArray(vector<int> &nums, int k) {
// write your code here
int n = nums.size();
if(k > n)
return INT_MIN;
vector<vector<int> > notTheLast(n+1,vector<int>(k+1,-10000));
vector<vector<int> > mustTheLast(n+1,vector<int>(k+1,-10000));
mustTheLast[0][0] = 0;
notTheLast[0][0] = 0 ;
for(int i = 1 ; i <= n; i++)
{
mustTheLast[i][0] = 0 ;
notTheLast[i][0] = 0;
for(int j = 1 ; j <= k; j++)
{
mustTheLast[i][j] = max(mustTheLast[i-1][j] + nums[i-1] ,notTheLast[i-1][j-1] + nums[i-1]);
notTheLast[i][j] = max(notTheLast[i-1][j] ,mustTheLast[i][j]);
}
}
return notTheLast[n][k];
}
};