#2218
Maximum Value of K Coins From Piles
HardArrayDynamic ProgrammingPrefix SumDynamic ProgrammingPrefix Sum
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n * k) |
| Space | O(1) | O(k) |
💡
Intuition
Time O(n * k)Space O(k)
The optimal solution uses dynamic programming to efficiently calculate the maximum value of coins we can collect by considering the best choices from each pile incrementally.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a DP array where dp[j] represents the maximum value we can obtain with j coins.
- 2Step 2: Iterate through each pile and for each pile, update the DP array from the back to avoid overwriting previous results.
- 3Step 3: For each pile, consider taking 0 to min(k, number of coins in the pile) coins and update the DP array accordingly.
solution.py9 lines
1def maxCoins(piles, k):
2 dp = [0] * (k + 1)
3 for pile in piles:
4 current_sum = 0
5 for j in range(min(len(pile), k)):
6 current_sum += pile[j]
7 for x in range(k, j, -1):
8 dp[x] = max(dp[x], dp[x - j - 1] + current_sum)
9 return dp[k]ℹ
Complexity note: The complexity is O(n * k) because we iterate through each pile and for each pile, we potentially update the DP array for k coins.
- 1Dynamic programming allows us to build solutions incrementally.
- 2Understanding how to manage state transitions in DP is crucial.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.