cpp: add “1800. Maximum Ascending Subarray Sum”
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
1266061643
commit
0308502e2d
1 changed files with 36 additions and 0 deletions
36
cpp/maximum-ascending-subarray-sum.cpp
Normal file
36
cpp/maximum-ascending-subarray-sum.cpp
Normal file
|
@ -0,0 +1,36 @@
|
||||||
|
#include <algorithm>
|
||||||
|
#include <cassert>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
class Solution {
|
||||||
|
public:
|
||||||
|
int maxAscendingSum(const std::vector<int> &nums) {
|
||||||
|
if (nums.empty()) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
int found = nums[0];
|
||||||
|
int current = nums[0];
|
||||||
|
|
||||||
|
for (auto i = 1u; i < nums.size(); ++i) {
|
||||||
|
if (nums[i] > nums[i - 1]) {
|
||||||
|
current += nums[i];
|
||||||
|
} else {
|
||||||
|
current = nums[i];
|
||||||
|
}
|
||||||
|
found = std::max(found, current);
|
||||||
|
}
|
||||||
|
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
Solution s;
|
||||||
|
|
||||||
|
assert(s.maxAscendingSum(std::vector{10, 20, 30, 5, 10, 50}) == 65);
|
||||||
|
assert(s.maxAscendingSum(std::vector{10, 20, 30, 40, 50}) == 150);
|
||||||
|
assert(s.maxAscendingSum(std::vector{12, 17, 15, 13, 10, 11, 12}) == 33);
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
Loading…
Reference in a new issue