题目:
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.
分析:
由题可知,需要用动态规划来解决问题。一开始我在遍历过程中只用了一个量,发现难以解决和的结果先下降再升高的状况。后来我改用两个量来遍历,即一个量用来保存遍历过程中出现的最大值,另一个量用来判断是否还有更大的值。
代码:
#include <iostream> #include <vector> #include <algorithm> using namespace std; class Solution { public: int maxSubArray(vector<int>& nums) { int res = nums[0]; int sum = 0; for (int i = 0; i < nums.size(); i++) { sum += nums[i]; res = max(sum, res); sum = max(sum,0); } return res; } };