Suppose we have an array of positive values called nums, we have to find the maximum possible sum of an ascending subarray in nums. We can say a subarray [nums_l, nums_l+1, ..., nums_r-1, nums_r] is ascending when for all i where l <= i < r, nums_i < nums_i+1.
So, if the input is like nums = [15,25,35,5,15,55], then the output will be 75 as [5,15,55] is increasing subarray with maximum sum.
To solve this, we will follow these steps −
total:= nums[0]
max_total:= nums[0]
for i in range 1 to size of nums, do
if nums[i] > nums[i-1], then
total := total + nums[i]
otherwise,
total:= nums[i]
if total > max_total, then
max_total:= total
return max_total
Let us see the following implementation to get better understanding −
Example
def solve(nums): total=nums[0] max_total=nums[0] for i in range(1,len(nums)): if nums[i] > nums[i-1]: total+=nums[i] else: total=nums[i] if total > max_total: max_total=total return max_total nums = [15,25,35,5,15,55] print(solve(nums))
Input
[15,25,35,5,15,55]
Output
75