這是我參與8月更文挑戰的第7天,活動詳情查看:8月更文挑戰markdown
Given an array of positive integers nums, return the maximum possible sum of an ascending subarray in nums.less
A subarray is defined as a contiguous sequence of numbers in an array.oop
A subarray [nums[l], nums[l+1], ..., nums[r-1], nums[r]] is ascending if for all i where l <= i < r, nums[i] < nums[i+1]. Note that a subarray of size 1 is ascending.post
Example 1:spa
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:code
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:orm
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.
複製代碼
Example 4:leetcode
Input: nums = [100,10,1]
Output: 100
複製代碼
Note:get
1 <= nums.length <= 100
1 <= nums[i] <= 100
複製代碼
根據題意,就是給出一個正整數的列表 nums ,找出升序子列表的最大和。子序列就是列表 nums 中的若干個連續的元素組成的列表,升序列就是後一個元素的值比前一個元素的值要大,注意只有一個元素的子序列也算是升序列。思路:it
class Solution(object):
def maxAscendingSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1:
return nums[0]
total = nums[0]
max_result = nums[0]
for i in range(1, len(nums)):
e = nums[i]
if e>nums[i-1]:
total += e
max_result = max(max_result, total)
else:
total = e
return max_result
複製代碼
Runtime: 16 ms, faster than 93.91% of Python online submissions for Maximum Ascending Subarray Sum.
Memory Usage: 13.6 MB, less than 9.68% of Python online submissions for Maximum Ascending Subarray Sum.
複製代碼
原題連接:leetcode.com/problems/ma…
您的支持是我最大的動力