[LeetCode] Visit Array Positions to Maximize Score

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 position j such that i < j.
  • For each position i that you visit, you get a score of nums[i].
  • If you move from a position i to a position j and the parities of nums[i] and nums[j] differ, then you lose a score of x.

Return the maximum total score you can get.

Note that initially you have nums[0] points.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
long long maxScore(vector<int>& nums, int x) {
long long dp1 = nums[0] & 1 ? INT_MIN : nums[0], dp2 = nums[0] & 1 ? nums[0] : INT_MIN;
for(int i = 1; i < nums.size(); i++) {
if(nums[i] & 1) {
dp2 = max(dp2 + nums[i], dp1 + nums[i] - x);
} else {
dp1 = max(dp1 + nums[i], dp2 + nums[i] - x);
}
}
return max(dp1, dp2);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/07/22/PS/LeetCode/visit-array-positions-to-maximize-score/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.