From 0308502e2d5f011465fb282c54c69031655a1dce Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Mon, 22 Jan 2024 23:26:39 +0100 Subject: [PATCH] =?UTF-8?q?cpp:=20add=20=E2=80=9C1800.=20Maximum=20Ascendi?= =?UTF-8?q?ng=20Subarray=20Sum=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- cpp/maximum-ascending-subarray-sum.cpp | 36 ++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 cpp/maximum-ascending-subarray-sum.cpp 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; +}