Leetcode1800:最大升序子数组和
-
题目:
-
给你一个正整数组成的数组 nums ,返回 nums 中一个 升序 子数组的最大可能元素和。
子数组是数组中的一个连续数字序列。
已知子数组 [numsl, numsl+1, ..., numsr-1, numsr] ,若对所有 i(l <= i < r),numsi < numsi+1 都成立,则称这一子数组为 升序 子数组。注意,大小为 1 的子数组也视作 升序 子数组。
-
-
思路:遍历所有子数组,取最大值
-
代码如下:
class Solution { public int maxAscendingSum(int[] nums) { //记录临时子数组最大值 int res = nums[0]; //记录当前遍历的子数组的值 int max = nums[0]; int n = nums.length; for (int i = 1; i<n; i++){ if(nums[i]>nums[i-1]){ max += nums[i]; }else{ //记录相邻子数组的较大值 res = Math.max(res,max); //此处作为两个数组的分界,将重头计算子数组 max = nums[i]; } } return Math.max(res,max); } }