koenjazh-CNfresde
짬뽕얼큰하게의 맨땅에 헤딩 :: Maximum Ascending Subarray Sum

Leetcode Problem:

Summary

  • Find the maximum possible sum of an ascending subarray in a given array of positive integers.

Approach

  • The approach used is to initialize variables to store the maximum sum and the current sum of the ascending subarray
  • Then, iterate over the array from the second element to the last element
  • If the current element is less than or equal to the previous element, reset the current sum to 0
  • Otherwise, add the current element to the current sum and update the maximum sum if necessary.

Complexity

  • O(n), where n is the number of elements in the array.

Explain

  • The provided solution uses Kadane's algorithm with a twist to find the maximum ascending subarray sum
  • It initializes variables `ans` and `sum` to store the maximum sum and the current sum of the ascending subarray, respectively
  • Then, it iterates over the array from the second element to the last element
  • If the current element is less than or equal to the previous element, it resets the current sum to 0
  • Otherwise, it adds the current element to the current sum and updates the maximum sum if necessary
  • The time complexity of this solution is O(n), where n is the number of elements in the array.

Solution Code:


class Solution {
public:
    vector st;
    int maxAscendingSum(vector& nums) {
        int ans = nums[0];
        int sum = nums[0];
        for(int i = 1; i < nums.size(); i++){
            if(nums[i] <= nums[i-1]){
                sum = 0;
            }
            sum += nums[i];
            ans = max(ans, sum);
        }
        return ans;
    }
};

'알고리즘' 카테고리의 다른 글

Minimum Number of Pushes to Type Word II  (0) 2025.02.05
Kth Distinct String in an Array  (0) 2025.02.05
Range Sum of Sorted Subarray Sums  (0) 2025.02.04
Number of Senior Citizens  (0) 2025.02.04
Filling Bookcase Shelves  (0) 2025.02.04
블로그 이미지

짬뽕얼큰하게

,