LeetCode 2786. Visit Array Positions to Maximize Score
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 = 5Output: 13Explanation: 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 = 3Output: 20Explanation: 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
--------------------------------------------------
给定一个 0 索引的整数数组 nums 和一个正整数 x。
您最初位于数组中的位置 0,您可以根据以下规则访问其他位置:
如果您当前处于位置 i,那么您可以移动到任意位置 j,使得 i < j。
对于您访问的每个位置 i,您将获得 nums[i] 分数。
如果你从位置 i 移动到位置 j 并且 nums[i] 和 nums[j] 的奇偶性不同,那么你会失去 x 的分数。
返回您可以获得的最高总分。
请注意,最初您有 nums[0] 点。
------------------------------------------
用2个变量依次去存储每次到该位置时候的odd,even的值,最后max返回;
Runtime: 11 ms, faster than 100.00% of Java online submissions for Visit Array Positions to Maximize Score.
Memory Usage: 55.3 MB, less than 100.00% of Java online submissions for Visit Array Positions to Maximize Score.