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.
解题方法:
需要维护两个变量,global,local。global主要是记录历史最大和,然后与local的当前最大和比较。
使用动态规划,转移方程有两个,假设第i步的local[i]和global[i]已知,那么第i+1步的local[i + 1] = max{ nums[i] + local[i], nums[i + 1] },global[i + 1] = max{global[i], local[i + 1]}。
代码:
#include <iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> nums;
int s;
while(cin>>s){
nums.push_back(s);
}
int n = nums.size();
int local = nums[0];
int global = nums[0];
for(int i=1;i<n;i++){
local = nums[i] > nums[i] +local ? nums[i] : nums[i]+local;
global = global>local? global:local;
}
cout << global << endl;
return 0;
}