访问数组中的位置使分数最大
难度:
标签:
题目描述
You are given a 0-indexed integer array nums
and a positive integer x
.
You are initially at position 0
in the array and you can visit other positions according to the following rules:
- If you are currently in position
i
, then you can move to any positionj
such thati < j
. - For each position
i
that you visit, you get a score ofnums[i]
. - If you move from a position
i
to a positionj
and the parities ofnums[i]
andnums[j]
differ, then you lose a score ofx
.
Return the maximum total score you can get.
Note that initially you have nums[0]
points.
Example 1:
Input: nums = [2,3,6,1,9,2], x = 5 Output: 13 Explanation: We can visit the following positions in the array: 0 -> 2 -> 3 -> 4. The corresponding values are 2, 6, 1 and 9. Since the integers 6 and 1 have different parities, the move 2 -> 3 will make you lose a score of x = 5. The total score will be: 2 + 6 + 1 + 9 - 5 = 13.
Example 2:
Input: nums = [2,4,6,8], x = 3 Output: 20 Explanation: All the integers in the array have the same parities, so we can visit all of them without losing any score. The total score is: 2 + 4 + 6 + 8 = 20.
Constraints:
2 <= nums.length <= 105
1 <= nums[i], x <= 106
代码结果
运行时间: 166 ms, 内存: 30.7 MB
/*
* 思路:
* 使用Java Stream API来实现同样的逻辑。
* 我们将创建一个动态规划数组dp来存储每个位置的最大得分。
* 使用stream的方式来遍历和计算每个位置的最大得分。
*/
import java.util.stream.IntStream;
public class MaxScoreStream {
public int maxScore(int[] nums, int x) {
int n = nums.length;
int[] dp = new int[n];
dp[0] = nums[0];
IntStream.range(1, n).forEach(j -> {
dp[j] = nums[j];
dp[j] = IntStream.range(0, j)
.map(i -> (nums[i] % 2) != (nums[j] % 2) ? dp[i] + nums[j] - x : dp[i] + nums[j])
.max()
.orElse(dp[j]);
});
return IntStream.of(dp).max().orElse(0);
}
}
解释
方法:
本题解采用动态规划的思路来计算最大得分。定义两个变量 oddmax 和 evenmax,分别存储到达当前位置时,如果当前位置是奇数或偶数时能得到的最大分数。初始化时,根据 nums[0] 的奇偶性来设定 oddmax 和 evenmax 的初始值。遍历数组的每一个元素,根据当前元素的奇偶性更新 oddmax 和 evenmax。如果当前元素是奇数,则 oddmax 可以由前一个奇数直接加上当前值或由前一个偶数转换而来(减去x分)。同理,如果当前元素是偶数,则 evenmax 可以由前一个偶数直接加或由前一个奇数转换而来。最后,返回 oddmax 和 evenmax 中的较大值作为最终答案。
时间复杂度:
O(n)
空间复杂度:
O(1)
代码细节讲解
🦆
为什么选择动态规划作为解决这个问题的方法?
▷🦆
在动态规划的过程中,如何保证 oddmax 和 evenmax 只通过前一个状态更新,而不会被其他早期状态影响?
▷🦆
为什么在初始化时,未选择的奇数或偶数的起始最大分数是 -x 而不是 0 或其他值?
▷🦆
动态规划中,更新 oddmax 和 evenmax 的表达式是否考虑了所有可能的状态转移?
▷