动态规划----最大子序和
程序员文章站
2024-03-23 09:36:46
...
题目:
Maximum Subarray
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.
标签是动态规划但是没看出来哪里是……..感觉是很简单的一题……
c++代码(O(N)解法)
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int sum = nums[0];
int cur_sum = 0;
for (size_t i = 0; i < nums.size(); ++i) {
cur_sum += nums[i];
if (cur_sum > sum) sum = cur_sum;
if (cur_sum < 0 ) cur_sum = 0;
}
return sum;
}
};
上一篇: rxjs订阅发布实现数据通信
下一篇: java后台接收json数据