leetcode 1800. Maximum Ascending Subarray Sum(python)

這是我參與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

  • 若是 nums 長度爲 1 ,nums 自己就是升序列,直接返回 nums[0]
  • 不然使用 total 表示當前子列表的和, max_result 表示最終須要返回的最大和。遍歷 nums ,若是當前的元素小於等於前一個元素,那麼直接將 total 設置爲當前元素,表示從這裏開始日後找新的升序子列表。若是當前元素大於前一個元素,那麼當前的升序列表還能夠找下去,將該元素加入 total
  • 而後比較 total 和 max_result 的最大值來更新 max_result
  • 遍歷結束便可獲得最終的結果 max_result 。

解答

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…

您的支持是我最大的動力

相關文章
相關標籤/搜索