#2786
Visit Array Positions to Maximize Score
MediumArrayDynamic ProgrammingDynamic ProgrammingGreedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n²)Space O(n)
The optimal solution uses dynamic programming to maintain the maximum score achievable up to each position in the array. By considering the parity of the current position and the previous maximum scores, we can efficiently calculate the best score without redundant calculations.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a dp array where dp[i] represents the maximum score achievable at position i.
- 2Step 2: Set dp[0] = nums[0] since we start at the first position.
- 3Step 3: Iterate through the array, and for each position i, check all previous positions j (where j < i).
- 4Step 4: Update dp[i] based on whether the parities of nums[i] and nums[j] are the same or different, adjusting for score loss accordingly.
- 5Step 5: Return the maximum value in the dp array.
solution.py12 lines
1def maxScore(nums, x):
2 n = len(nums)
3 dp = [0] * n
4 dp[0] = nums[0]
5 for i in range(1, n):
6 dp[i] = nums[i]
7 for j in range(i):
8 if (nums[i] % 2) != (nums[j] % 2):
9 dp[i] = max(dp[i], dp[j] + nums[i] - x)
10 else:
11 dp[i] = max(dp[i], dp[j] + nums[i])
12 return max(dp)ℹ
Complexity note: The time complexity remains O(n²) due to the nested loops, but we gain clarity and structure with dynamic programming. The space complexity is O(n) due to the dp array used to store intermediate results.
- 1Understanding parity is crucial for calculating score adjustments.
- 2Dynamic programming helps break down the problem into manageable subproblems.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.