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.
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.
At each position, the best score depends on the parity of the last number you visited. Track the best score so far if the last number is even or odd. For each position, update the best score for its parity, considering a penalty if you switch parity.
Let best_even be the best score ending at an even number, and best_odd for odd. Initialize with the first number. For each next number, update the best for its parity by considering both staying with the same parity and switching (with penalty).
#include<vector>#include<algorithm>usingnamespace std;
classSolution {
public:longlong maxScore(vector<int>& nums, int x) {
longlong even = LLONG_MIN, odd = LLONG_MIN;
if (nums[0] %2==0) even = nums[0];
else odd = nums[0];
for (int i =1; i < nums.size(); ++i) {
int num = nums[i];
if (num %2==0)
even = max(even + num, odd + num - x);
else odd = max(odd + num, even + num - x);
}
returnmax(even, odd);
}
};
classSolution {
publiclongmaxScore(int[] nums, int x) {
long even = Long.MIN_VALUE, odd = Long.MIN_VALUE;
if (nums[0]% 2 == 0) even = nums[0];
else odd = nums[0];
for (int i = 1; i < nums.length; i++) {
int num = nums[i];
if (num % 2 == 0)
even = Math.max(even + num, odd + num - x);
else odd = Math.max(odd + num, even + num - x);
}
return Math.max(even, odd);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
funmaxScore(nums: IntArray, x: Int): Long {
var even = Long.MIN_VALUE
var odd = Long.MIN_VALUE
if (nums[0] % 2==0) even = nums[0].toLong() else odd = nums[0].toLong()
for (i in1 until nums.size) {
val num = nums[i].toLong()
if (nums[i] % 2==0)
even = maxOf(even + num, odd + num - x)
else odd = maxOf(odd + num, even + num - x)
}
return maxOf(even, odd)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from typing import List
classSolution:
defmaxScore(self, nums: List[int], x: int) -> int:
even = float('-inf')
odd = float('-inf')
if nums[0] %2==0:
even = nums[0]
else:
odd = nums[0]
for num in nums[1:]:
if num %2==0:
even = max(even + num, odd + num - x)
else:
odd = max(odd + num, even + num - x)
return max(even, odd)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
pubfnmax_score(nums: Vec<i64>, x: i64) -> i64 {
letmut even =i64::MIN;
letmut odd =i64::MIN;
if nums[0] %2==0 {
even = nums[0];
} else {
odd = nums[0];
}
for&num in&nums[1..] {
if num %2==0 {
even = even.max(odd + num - x).max(even + num);
} else {
odd = odd.max(even + num - x).max(odd + num);
}
}
even.max(odd)
}