난이도: Easy
문제 설명
Given an array of positive integers nums
, return the maximum possible sum of an ascending subarray in nums
.
A subarray is defined as a contiguous sequence of numbers in an array.
A subarray [numsl, numsl+1, ..., numsr-1, numsr]
is ascending if for all i
where l <= i < r
, numsi < numsi+1
. Note that a subarray of size 1
is ascending.
문제 예제
Example 1:
Input: nums = [10,20,30,5,10,50]
Output: 65
Explanation: [5,10,50] is the ascending subarray with the maximum sum of 65.
Example 2:
Input: nums = [10,20,30,40,50]
Output: 150
Explanation: [10,20,30,40,50] is the ascending subarray with the maximum sum of 150.
Example 3:
Input: nums = [12,17,15,13,10,11,12]
Output: 33
Explanation: [10,11,12] is the ascending subarray with the maximum sum of 33.
제한 사항
1 <= nums.length <= 100
1 <= nums[i] <= 100
✏️ Solution(솔루션)
class Solution:
def maxAscendingSum(self, nums: List[int]) -> int:
answer = nums[0]
n = len(nums)
sum_sub_array = nums[0]
for i in range(1, n):
if nums[i-1] < nums[i]:
sum_sub_array += nums[i]
else:
sum_sub_array = nums[i]
answer = max(answer, sum_sub_array)
return answer
sum_sub_array 변수를 만들어 subarray의 합을 구해나갔다.
nums의 현재 요소와 이전 요소를 비교해 현재 요소가 더 크다고 하면 sum_sub_array에 현재 요소를 더해주었다.
이렇게 하면 ascending subarray의 합을 구할 수 있기 때문이다.
만약 이를 만족하지 않으면 ascending subarray가 아니기 때문에 sum_sub_array를 현재 요소로 초기화해주었다.
이를 모든 요소를 탐색할 때까지 반복했고, 매 반복문마다 answer = max(answer, sum_sub_array)를 통해 최대 합을 구했다.
마지막에 answer를 return하여 정답을 맞을 수 있었다.
문제: 1800. Maximum Ascending Subarray Sum
깃허브: github
algorithmPractice/LeetCode/1927-maximum-ascending-subarray-sum at main · laewonJeong/algorithmPractice
하루 한 문제 챌린지. Contribute to laewonJeong/algorithmPractice development by creating an account on GitHub.
github.com