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);
}
}
LeetCode 1800: 最大升序子数组和的算法解析
本文详细介绍了LeetCode第1800题的解决方案,题目要求找到正整数数组中的最大升序子数组和。思路是遍历数组,动态维护当前子数组的最大值和全局最大值。代码实现中通过比较相邻元素判断是否继续累加,从而找到最大升序子数组的和。
689

被折叠的 条评论
为什么被折叠?



