|
| 1 | +// Source : https://leetcode.com/problems/maximum-ascending-subarray-sum/ |
| 2 | +// Author : Hao Chen |
| 3 | +// Date : 2021-03-21 |
| 4 | + |
| 5 | +/***************************************************************************************************** |
| 6 | + * |
| 7 | + * Given an array of positive integers nums, return the maximum possible sum of an ascending subarray |
| 8 | + * in nums. |
| 9 | + * |
| 10 | + * A subarray is defined as a contiguous sequence of numbers in an array. |
| 11 | + * |
| 12 | + * A subarray [numsl, numsl+1, ..., numsr-1, numsr] is ascending if for all i where l <= i < r, numsi |
| 13 | + * < numsi+1. Note that a subarray of size 1 is ascending. |
| 14 | + * |
| 15 | + * Example 1: |
| 16 | + * |
| 17 | + * Input: nums = [10,20,30,5,10,50] |
| 18 | + * Output: 65 |
| 19 | + * Explanation: [5,10,50] is the ascending subarray with the maximum sum of 65. |
| 20 | + * |
| 21 | + * Example 2: |
| 22 | + * |
| 23 | + * Input: nums = [10,20,30,40,50] |
| 24 | + * Output: 150 |
| 25 | + * Explanation: [10,20,30,40,50] is the ascending subarray with the maximum sum of 150. |
| 26 | + * |
| 27 | + * Example 3: |
| 28 | + * |
| 29 | + * Input: nums = [12,17,15,13,10,11,12] |
| 30 | + * Output: 33 |
| 31 | + * Explanation: [10,11,12] is the ascending subarray with the maximum sum of 33. |
| 32 | + * |
| 33 | + * Example 4: |
| 34 | + * |
| 35 | + * Input: nums = [100,10,1] |
| 36 | + * Output: 100 |
| 37 | + * |
| 38 | + * Constraints: |
| 39 | + * |
| 40 | + * 1 <= nums.length <= 100 |
| 41 | + * 1 <= nums[i] <= 100 |
| 42 | + ******************************************************************************************************/ |
| 43 | + |
| 44 | +class Solution { |
| 45 | +public: |
| 46 | + int maxAscendingSum(vector<int>& nums) { |
| 47 | + int maxSum = nums[0]; |
| 48 | + int sum = maxSum; |
| 49 | + for(int i=1; i<nums.size(); i++) { |
| 50 | + if (nums[i] > nums[i-1]) { |
| 51 | + sum += nums[i]; |
| 52 | + }else{ |
| 53 | + maxSum = maxSum < sum ? sum : maxSum; |
| 54 | + sum = nums[i]; |
| 55 | + } |
| 56 | + } |
| 57 | + maxSum = maxSum < sum ? sum : maxSum; |
| 58 | + return maxSum; |
| 59 | + } |
| 60 | +}; |
0 commit comments