Visit Array Positions to Maximize Score - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,3,6,-5], x = 10
Output: 8
💡 Note: We can visit positions 0 → 2. Score = 2 + 6 - 10 (parity penalty) = -2. Or visit 0 → 1 → 2: 2 + 3 - 10 + 6 - 10 = -9. Best path: 0 → 2 gives 2 + 6 = 8 (no penalty needed if we optimize properly).
Example 2 — All Same Parity
$ Input: nums = [2,4,6,8], x = 3
Output: 20
💡 Note: All numbers are even, so no parity penalties. Visit all positions: 2 + 4 + 6 + 8 = 20.
Example 3 — High Penalty
$ Input: nums = [1,5], x = 10
Output: 1
💡 Note: Both numbers are odd. Start at position 0 with score 1. Moving to position 1 would add 5 but cost 0 (same parity), giving total 6. But we start with nums[0] = 1, so visiting just position 0 gives score 1.

Constraints

  • 1 ≤ nums.length ≤ 105
  • -106 ≤ nums[i] ≤ 106
  • 1 ≤ x ≤ 106

Visualization

Tap to expand
Visit Array Positions to Maximize Score236-5evenoddevenoddPenalty x = 10 when switching between odd ↔ evenBest PathScorePositions: 0,22 + 6 = 8🎯 Key Insight: Track optimal scores for even/odd endings separately
Understanding the Visualization
1
Input Array
nums = [2,3,6,-5], x = 10 (penalty for parity change)
2
Track States
Maintain best scores for even/odd endings at each step
3
Optimal Score
Return maximum of both ending states
Key Takeaway
🎯 Key Insight: Separate tracking of even/odd ending states eliminates the need to explore all paths
Asked in
Amazon 15 Google 12 Microsoft 8
28.4K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen