Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
非常经典的DP题目
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int a = nums[0];
int b = nums[0];
for (int i = 1; i < nums.size(); i++) {
a = max(nums[i] + a, nums[i]);
b = max(a, b);
}
return b;
}
};
同时由这道题引申出来的还有许多,比较经典的是第K个最大连续子序列的和
这里用最小堆解决
//我们求出所有连续子序列和
//将前k个放入堆,则Q.top即最小/第k大
//遍历余下所有元素,若大于top,则说明在最终K位置的左边,pop and push
//若小于,则说明在右边,对结果不影响,continue
int K(vector<int>nums, int k){
int n = nums.size();
int sum[n+1];
int i, j, k;
sum[0] = 0;
//store sum from begin to i
for (i = 1; i <= n; i++) {
sum[i] = nums[i-1] + sum[i-1];
}
priority_queue<int, vector<int>, greater<int> >Q;
for (i = 1; i <= n; i++) {
for (j = i; j <= n; j++) { //traversl all sub
int tmp = sum[j] - sum[i-1]; //sum of [i : j] equals [j] - [i-1]
if (Q.size() < k)
Q.push(tmp);
else {
if (Q.top < tmp){
Q.pop();
Q.push(tmp);
}
}
}
}