diff --git a/cpp/maximum-ascending-subarray-sum.cpp b/cpp/maximum-ascending-subarray-sum.cpp new file mode 100644 index 0000000..14f4566 --- /dev/null +++ b/cpp/maximum-ascending-subarray-sum.cpp @@ -0,0 +1,36 @@ +#include +#include +#include + +class Solution { + public: + int maxAscendingSum(const std::vector &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; +}