调试中...
调试中...
题目描述
题目描述
题解
题解
提交记录
提交记录
代码
代码
测试用例
测试用例
测试结果
测试结果
中等
相关标签
相关企业
提示

给你一个长度为 n 的整数数组 nums

子数组 nums[l..r](其中 0 <= l <= r < n)的 成本 定义为:

cost(l, r) = nums[l] - nums[l + 1] + ... + nums[r] * (−1)r − l

你的任务是将 nums 分割成若干子数组,使得所有子数组的成本之和 最大化,并确保每个元素 正好 属于一个子数组。

具体来说,如果 nums 被分割成 k 个子数组,且分割点为索引 i1, i2, ..., ik − 1(其中 0 <= i1 < i2 < ... < ik - 1 < n - 1),则总成本为:

cost(0, i1) + cost(i1 + 1, i2) + ... + cost(ik − 1 + 1, n − 1)

返回在最优分割方式下的子数组成本之和的最大值。

注意:如果 nums 没有被分割,即 k = 1,则总成本即为 cost(0, n - 1)

 

示例 1:

输入: nums = [1,-2,3,4]

输出: 10

解释:

一种总成本最大化的方法是将 [1, -2, 3, 4] 分割成子数组 [1, -2, 3][4]。总成本为 (1 + 2 + 3) + 4 = 10

示例 2:

输入: nums = [1,-1,1,-1]

输出: 4

解释:

一种总成本最大化的方法是将 [1, -1, 1, -1] 分割成子数组 [1, -1][1, -1]。总成本为 (1 + 1) + (1 + 1) = 4

示例 3:

输入: nums = [0]

输出: 0

解释:

无法进一步分割数组,因此答案为 0。

示例 4:

输入: nums = [1,-1]

输出: 2

解释:

选择整个数组,总成本为 1 + 1 = 2,这是可能的最大成本。

 

提示:

  • 1 <= nums.length <= 105
  • -109 <= nums[i] <= 109
通过次数
6.3K
提交次数
16.5K
通过率
37.8%

相关标签

相关企业

提示 1
The problem can be solved using dynamic programming.

提示 2
Since we can always start a new subarray, the problem is the same as selecting some elements in the array and flipping their signs to negative to maximize the sum. However, we cannot flip the signs of 2 consecutive elements, and the first element in the array cannot be negative.

提示 3
Let dp[i][0/1] be the largest sum we can get for prefix nums[0..i], where dp[i][0] is the maximum if the ith element wasn't flipped, and dp[i][1] is the maximum if the ith element was flipped.

提示 4
Based on the restriction:
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1]) + nums[i]
dp[i][1] = dp[i - 1][0] - nums[i]

提示 5
The initial state is:
dp[1][0] = nums[0] + nums[1]
dp[1][1] = nums[0] - nums[1]
and the answer is max(dp[n - 1][0], dp[n - 1][1]).

提示 6
Can you optimize the space complexity?

评论 (0)

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