BM72. 连续子数组的最大和
描述
示例1
输入:
[1,-2,3,10,-4,7,2,-5]
输出:
18
说明:
经分析可知,输入数组的子数组[3,10,-4,7,2]可以求得最大和为18示例2
输入:
[2]
输出:
2
示例3
输入:
[-10]
输出:
-10
C++ 解法, 执行用时: 18ms, 内存消耗: 5760KB, 提交时间: 2022-01-29
static const auto io_sync_off = []() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); return nullptr; }(); class Solution { public: int FindGreatestSumOfSubArray(vector<int> array) { int len=array.size(); int mx=-2e8; int now=0; for(int i=0;i<len;i++){ now+=array[i]; mx=max(mx,now); if(now<0){ now=0; } } return mx; } };
C++ 解法, 执行用时: 18ms, 内存消耗: 5760KB, 提交时间: 2022-01-12
static const auto io_sync_off = []() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); return nullptr; }(); class Solution { public: int FindGreatestSumOfSubArray(vector<int> array) { int sum = array[0], temp = sum; for(int i = 1; i < array.size(); ++i) { if(sum < 0) { sum = array[i]; } else { sum += array[i]; } temp = temp > sum ? temp : sum; } return temp; } };
C++ 解法, 执行用时: 18ms, 内存消耗: 5772KB, 提交时间: 2021-12-15
static const auto io_sync_off = []() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); return nullptr; }(); class Solution { public: int FindGreatestSumOfSubArray(vector<int> array) { int sum = array[0], before = sum; int range = array.size(); for(int i=1; i<range; i++) { sum += array[i]; if(array[i] < 0 && before < sum - array[i]) before = sum - array[i]; if(array[i] > sum) sum = array[i]; } return sum > before ? sum : before; } };
C++ 解法, 执行用时: 18ms, 内存消耗: 5788KB, 提交时间: 2022-01-08
class Solution { public: int FindGreatestSumOfSubArray(vector<int> nums) { int sum = 0; int res = nums[0]; for(int i = 0; i < nums.size();i++){ sum += nums[i]; res = max(res,sum); if(sum <= 0){ sum = 0; } } return res; } }; static const auto speedup = []{ std::ios::sync_with_stdio(false); std::cin.tie(nullptr); return nullptr; }();
C++ 解法, 执行用时: 19ms, 内存消耗: 5736KB, 提交时间: 2022-02-12
static const auto io_sync_off = []() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); return nullptr; }(); class Solution { public: int FindGreatestSumOfSubArray(vector<int> array) { int ret = INT_MIN; int count = 0; for(int k : array){ if(count < 0) count = k; else count += k; ret = max(ret,count); } return ret; } };