cpp: add “1800. Maximum Ascending Subarray Sum”

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-01-22 23:26:39 +01:00
parent 1266061643
commit 0308502e2d
Signed by: mfocko
GPG key ID: 7C47D46246790496

View 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;
}