This approach uses dynamic programming to find the maximum value of k coins from the given piles. We maintain a DP table where dp[i][j] represents the maximum value of coins we can obtain using the first i piles and j picks.
The main idea is to update this table by considering the top coin from the current pile, and deciding whether or not to pick it. We also keep track of cumulative sums for quicker reference.
Time Complexity: O(n * k * m), where n is the number of piles, k is the number of coins to pick, and m is the average number of coins in each pile.
Space Complexity: O(n * k)
1import java.util.List;
2
3public class Solution {
4 public int maxValueOfCoins(List<List<Integer>> piles, int k) {
5 int n = piles.size();
6 int[][] dp = new int[n + 1][k + 1];
7
8 for (int i = 1; i <= n; i++) {
9 List<Integer> currentPile = piles.get(i - 1);
10 int pileSum = 0;
11 for (int j = 0; j < currentPile.size(); j++) {
12 pileSum += currentPile.get(j);
13 for (int x = k; x >= j + 1; x--) {
14 dp[i][x] = Math.max(dp[i][x], dp[i - 1][x - j - 1] + pileSum);
15 }
16 }
17 }
18
19 return dp[n][k];
20 }
21
22 // Example usage:
23 // List<List<Integer>> piles = Arrays.asList(Arrays.asList(1, 100, 3), Arrays.asList(7, 8, 9));
24 // int k = 2;
25 // int result = new Solution().maxValueOfCoins(piles, k); // Output: 101
26}
The Java solution makes use of a 2D array dp
to store the maximum values for each pile and possible pick count up to k. It updates the dp array iteratively using the cumulative sums gathered from each current pile.
This approach involves greedy selection to achieve a near-optimal solution. The idea is to always select the coin with the highest value from a potential list of top coins from each pile, and repeat this k times.
This method might not guarantee the absolute optimal solution due to local-optimal greediness but can offer a reasonable approximation for certain constraints and datasets.
Time Complexity: O(k log n), as we perform k heap operations on n piles.
Space Complexity: O(n), due to storing piles in the heap.
1import heapq
2
3def maxValueOfCoins(piles, k):
4 max_heap = []
5 for pile in piles:
6 heapq.heappush(max_heap, (-pile[0], 0, pile))
7
8 total_value = 0
9 for _ in range(k):
10 value, index, pile = heapq.heappop(max_heap)
11 total_value -= value
12 if index + 1 < len(pile):
13 heapq.heappush(max_heap, (-pile[index + 1], index + 1, pile))
14 return total_value
15
16# Example usage:
17piles = [[1, 100, 3], [7, 8, 9]]
18k = 2
19print(maxValueOfCoins(piles, k)) # Output: 101
The solution uses a max-heap to store the possible top coins from each pile. We keep track of the coin values along with their indices and iteratively pop and push from/to the heap as we select the highest value coins.