最大子数组和
#include <iostream> using namespace std; struct MaxRangResult { int max_; int start_; int end_; }; MaxRangResult FindMaxRang(const vector<int>& nums) { MaxRangResult result{0, 0, 0}; int sum = 0; int current = 0; for (int i = 0, size = nums.size(); i < size; ++i) { if (sum < 0) { sum = nums[i]; current = i; } else { sum += nums[i]; } if (result.max_ < sum) { result.max_ = sum; result.start_ = current; result.end_ = i; } } return result; } int main() { vector<int> nums{3, -4, 1, 3}; MaxRangResult result = FindMaxRang(nums); getchar(); return 0; }