LeetCode 1561: Maximum Number of Coins You Can Get
Problem Description
Explanation
To maximize the number of coins you can get, you need to strategically choose the piles in a way that allows you to get the second highest number of coins in each triplet. We can achieve this by sorting the piles in descending order and then selecting every third pile (starting from the second pile) as your pick. This way, you will always get the second highest number of coins in each triplet.
Algorithm:
- Sort the piles array in descending order.
- Iterate through the sorted array and select every third element starting from the second element.
- Sum up all the selected elements to get the maximum number of coins you can have.
Time Complexity:
The time complexity of this algorithm is O(n log n) due to the sorting operation.
Space Complexity:
The space complexity of this algorithm is O(1) as we are not using any extra space.
Solutions
class Solution {
public int maxCoins(int[] piles) {
Arrays.sort(piles);
int n = piles.length / 3;
int maxCoins = 0;
for (int i = n; i < 3 * n; i += 2) {
maxCoins += piles[i];
}
return maxCoins;
}
}
Loading editor...