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 positionjsuch thati < j. - For each position
ithat you visit, you get a score ofnums[i]. - If you move from a position
ito a positionjand the parities ofnums[i]andnums[j]differ, then you lose a score ofx.
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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code