1800. Maximum Ascending Subarray Sum #1269
-
Topics: Given an array of positive integers A subarray is defined as a contiguous sequence of numbers in an array. A subarray Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the maximum possible sum of an ascending subarray in a given array of positive integers. An ascending subarray is defined as a contiguous sequence where each element is strictly larger than the previous one. Approach
Let's implement this solution in PHP: 1800. Maximum Ascending Subarray Sum <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function maxAscendingSum($nums) {
$max_sum = $current_sum = $nums[0];
$n = count($nums);
for ($i = 1; $i < $n; $i++) {
if ($nums[$i] > $nums[$i-1]) {
$current_sum += $nums[$i];
} else {
$current_sum = $nums[$i];
}
if ($current_sum > $max_sum) {
$max_sum = $current_sum;
}
}
return $max_sum;
}
// Example usage:
$nums1 = [10,20,30,5,10,50];
$nums2 = [10,20,30,40,50];
$nums3 = [12,17,15,13,10,11,12];
echo maxAscendingSum($nums1) . "\n"; // Output: 65
echo maxAscendingSum($nums2) . "\n"; // Output: 150
echo maxAscendingSum($nums3) . "\n"; // Output: 33
?> Explanation:
This approach efficiently tracks the maximum sum of ascending subarrays in a single pass through the array, resulting in a time complexity of O(n), where n is the length of the array. This ensures optimal performance even for the upper constraint of the problem. |
Beta Was this translation helpful? Give feedback.
We need to find the maximum possible sum of an ascending subarray in a given array of positive integers. An ascending subarray is defined as a contiguous sequence where each element is strictly larger than the previous one.
Approach
max_sum
andcurrent_sum
, to the value of the first element in the array. These will track the maximum sum found so far and the sum of the current ascending subarray, respectively.current_sum
.current_sum
to the curre…