Leetcode 1800. Maximum Ascending Subarray Sum
Given an array nums
of positive integers, find the maximum possible sum of an ascending subarray in the input array.
Input: nums = [10, 20, 30, 5, 10, 50]
Output: 65
Explanation: [10, 20, 30] is the ascending subarray with the maximum sum.
Here’s the C++ code to solve this problem:
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int maxAscendingSum(vector<int>& nums) {
if (nums.empty()) return 0;
int maxSum = nums[0];
int currentSum = nums[0];
for (size_t i = 1; i < nums.size(); ++i) {
if (nums[i] > nums[i - 1]) {
currentSum += nums[i];
} else {
maxSum = max(maxSum, currentSum);
currentSum = nums[i];
}
}
return max(maxSum, currentSum);
}
};
maxSum
and currentSum
are both initialized to the first element of the array.currentSum
.maxSum
with the maximum of maxSum
and currentSum
, then reset currentSum
to the current element.currentSum
is considered.This solution ensures an efficient traversal of the array, updating the sums as necessary without needing additional space beyond a few ints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?