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: 6
💡 Note: Both numbers are odd. Start at position 0 with score 1. Moving to position 1 adds 5 with no penalty (same parity), giving total score 1 + 5 = 6.

Constraints

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

Visualization

Tap to expand
Visit Array Positions to Maximize Score INPUT Array nums: 0 1 2 3 2 3 6 -5 Even Odd nums = [2, 3, 6, -5] x = 10 (penalty) Start at index 0 Movement: i --> j (where i < j) i=0 j can visit ALGORITHM STEPS 1 Track by Parity dp[0]=even max, dp[1]=odd max 2 Initialize dp[0]=2 (even), dp[1]=-INF 3 Process Each Element Same parity: no penalty Diff parity: subtract x 4 Return max(dp) Best score from either parity DP Transitions: i=0: dp=[2, -INF] i=1: dp[1]=max(-INF+3, 2-10+3) dp=[2, -5] i=2: dp[0]=max(2+6, -5-10+6) dp=[8, -5] FINAL RESULT Optimal Path: 2 3 6 -5 skip odd Score Calculation: Start at 0: +2 Jump to 2: +6 Total: 8 OUTPUT 8 OK - Maximum Score Key Insight: Track maximum scores separately for even and odd parities. For each element, choose the best previous score: same parity (no penalty) or different parity (subtract x). This reduces the problem from O(n^2) to O(n) by only tracking two states instead of all previous positions. TutorialsPoint - Visit Array Positions to Maximize Score | Optimal Solution (DP by Parity)
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