topic
leetcode53. Maximum sub-order sum
Given an integer array nums, find a continuous sub-array with the largest sum (the sub-array contains at least one element), and return the largest sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: The sum of consecutive subarrays [4,-1,2,1] is the largest, which is 6.
Code
- Ideas
- Dynamic programming
- Assuming that the maximum sub-order sum of the following element i as the ending is max_ending_here[i], the relationship is as follows:
max_ending_here[i] = max(max_ending_here[i-1] + nums[i], nums[i]) (i > 0)
- Assuming that the maximum sub-order sum of the following element i as the ending is max_ending_here[i], the relationship is as follows:
- Dynamic programming
- Code
// C
int maxSubArray(int* nums, int numsSize) {
int max_ending_here = nums[0];
int max_so_for = nums[0];
for (int i = 1; i < numsSize; ++i) {
max_ending_here = (max_ending_here + nums[i]) > nums[i]
? (max_ending_here + nums[i]): nums[i];
max_so_for = max_ending_here > max_so_for ? max_ending_here : max_so_for;
}
return max_so_for;
}
// C++
#include <algorithm>
#include <vector>
using namespace std;
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int max_ending_here = nums[0];
int max_so_for = nums[0];
for (int i = 1; i < nums.size(); ++i) {
max_ending_here = std::max(max_ending_here + nums[i], nums[i]);
max_so_for = std::max(max_ending_here, max_so_for);
}
return max_so_for;
}
};
- note
// 以下语句可换一种写法
max_ending_here = std::max(max_ending_here + nums[i], nums[i]);
// 如下:
if (max_ending_here > 0){
// max_ending_here + nums[i] > nums[i]
max_ending_here = max_ending_here + nums[i];
}else{
max_ending_here = nums[i];
}
test
#include <iostream>
int main() {
{
// C
int nums[] = {
-2, 1, -3, 4, -1, 2, 1, -5, 4};
int n = sizeof(nums) / sizeof(nums[0]);
cout << maxSubArray(nums, n) << endl;
}
{
// C++
vector<int> nums{
-2, 1, -3, 4, -1, 2, 1, -5, 4};
Solution s;
cout << s.maxSubArray(nums) << endl;
}
cin.get();
return 0;
}
- result
6
6