leetcode在力扣 App 中打开
调试中...
调试中...
题目描述
题目描述
题解
题解
提交记录
提交记录
代码
代码
测试用例
测试用例
测试结果
测试结果
困难
相关标签
相关企业
提示

给你一个下标从 0 开始的整数数组 nums 。

nums 一个长度为 k 的 子序列 指的是选出 k 个 下标 i0 < i1 < ... < ik-1 ,如果这个子序列满足以下条件,我们说它是 平衡的 :

  • 对于范围 [1, k - 1] 内的所有 j ,nums[ij] - nums[ij-1] >= ij - ij-1 都成立。

nums 长度为 1 的 子序列 是平衡的。

请你返回一个整数,表示 nums 平衡 子序列里面的 最大元素和 。

一个数组的 子序列 指的是从原数组中删除一些元素(也可能一个元素也不删除)后,剩余元素保持相对顺序得到的 非空 新数组。

 

示例 1:

输入:nums = [3,3,5,6]
输出:14
解释:这个例子中,选择子序列 [3,5,6] ,下标为 0 ,2 和 3 的元素被选中。
nums[2] - nums[0] >= 2 - 0 。
nums[3] - nums[2] >= 3 - 2 。
所以,这是一个平衡子序列,且它的和是所有平衡子序列里最大的。
包含下标 1 ,2 和 3 的子序列也是一个平衡的子序列。
最大平衡子序列和为 14 。

示例 2:

输入:nums = [5,-1,-3,8]
输出:13
解释:这个例子中,选择子序列 [5,8] ,下标为 0 和 3 的元素被选中。
nums[3] - nums[0] >= 3 - 0 。
所以,这是一个平衡子序列,且它的和是所有平衡子序列里最大的。
最大平衡子序列和为 13 。

示例 3:

输入:nums = [-2,-1]
输出:-1
解释:这个例子中,选择子序列 [-1] 。
这是一个平衡子序列,而且它的和是 nums 所有平衡子序列里最大的。

 

提示:

  • 1 <= nums.length <= 105
  • -109 <= nums[i] <= 109
通过次数
3.4K
提交次数
8.5K
通过率
39.8%


相关企业

提示 1
Let dp[x] represent the maximum sum of a balanced subsequence ending at x.

提示 2
Rewriting the formula nums[ij] - nums[ij-1] >= ij - ij-1 gives nums[ij] - ij >= nums[ij-1] - ij-1.

提示 3
So, for some index x, we need to find an index y, y < x, such that dp[x] = nums[x] + dp[y] is maximized, and nums[x] - x >= nums[y] - y.

提示 4
There are many ways to achieve this. One method involves sorting the values of nums[x] - x for all indices x and using a segment/Fenwick tree with coordinate compression.

提示 5
Hence, using a dictionary or map, let's call it dict, where dict[nums[x] - x] represents the position of the value, nums[x] - x, in the segment tree.

提示 6
The tree is initialized with zeros initially.

提示 7
For indices x in order from [0, n - 1], dp[x] = max(nums[x], nums[x] + the maximum query from the tree in the range [0, dict[nums[x] - x]]), and if dp[x] is greater than the value in the tree at position dict[nums[x] - x], we update the value in the tree.

提示 8
The answer to the problem is the maximum value in dp.


评论 (0)

贡献者
© 2025 领扣网络(上海)有限公司
0 人在线
行 1,列 1
运行和提交代码需要登录
nums =
[3,3,5,6]
Source