Problem Description
You are given a 0-indexed integer array nums and a positive integer x. You start at position 0 (gaining nums[0] points), and you can move to any position j > i. For every move, you add nums[j] to your score. Additionally, if nums[i] and nums[j] have different parities, you lose x points. The goal is to choose a sequence of moves (possibly skipping some positions) so that the total score is maximized.
Key Insights
- The decision at each position depends only on the parity of the current number and the best score you can have ending in an even or odd number.
- Use dynamic programming with two variables: bestEven (maximum score when last visited number is even) and bestOdd (maximum score when last visited number is odd).
- When considering a new number, there are two cases:
- If the number has the same parity as the last visited number, simply add the value.
- If the parity differs, add the value but subtract x.
- It is not necessary to choose every position; update the best scores as you iterate to account for potential skips.
Space and Time Complexity
Time Complexity: O(n) because we iterate through the array only once. Space Complexity: O(1) since we only maintain two state variables.
Solution
We use a dynamic programming approach by maintaining two variables: bestEven and bestOdd. They store the maximum score possible so far ending with an even or odd number, respectively. Initialize these based on the parity of nums[0]. For each subsequent element in nums, update the corresponding state by considering whether transitioning from the same or the opposite parity is more beneficial (taking into account the penalty x when parities differ). Finally, the answer will be the maximum of the two states. This greedy DP strategy ensures that we always pick the optimal score up to the current index.