There are 3n piles of coins of varying size, you and your friends will take piles of coins as follows:
- In each step, you will choose any 3 piles of coins (not necessarily consecutive).
- Of your choice, Alice will pick the pile with the maximum number of coins.
- You will pick the next pile with maximum number of coins.
- Your friend Bob will pick the last pile.
- Repeat until there are no more piles of coins.
Given an array of integers piles
where piles[i]
is the number of coins in the ith
pile.
Return the maximum number of coins which you can have.
一共有3n堆大小不同的硬币,你和你的朋友将按照以下方式取一堆硬币:
在每一步,你将选择任何3堆硬币(不一定是连续的)。
根据你的选择,爱丽丝会挑出硬币最多的那一堆。
你将选择下一堆硬币的最大数量。
你的朋友鲍勃会挑最后一堆。
重复,直到没有更多的硬币堆。
给定一个整数数组,其中,成堆[i]是第i堆中硬币的数量。
归还你可以拥有的最大数量的硬币。
Example 1:
Input: piles = [2,4,1,2,7,8] Output: 9 Explanation: Choose the triplet (2, 7, 8), Alice Pick the pile with 8 coins, you the pile with 7 coins and Bob the last one. Choose the triplet (1, 2, 4), Alice Pick the pile with 4 coins, you the pile with 2 coins and Bob the last one. The maximum number of coins which you can have are: 7 + 2 = 9. On the other hand if we choose this arrangement (1, 2, 8), (2, 4, 7) you only get 2 + 4 = 6 coins which is not optimal.
选三组(2,7,8),爱丽丝选有8枚硬币的那一组,你选有7枚硬币的那一组,鲍勃选最后一组。
选三组(1,2,4),爱丽丝选有4枚硬币的那一堆,你选有2枚硬币的那一堆,鲍勃选最后一枚。
你能拥有的硬币的最大数量是:7 + 2 = 9。
另一方面,如果我们选择这种排列(1,2,8)(2,4,7)你只能得到2 + 4 = 6枚硬币,这不是最优的。
Example 2:
Input: piles = [2,4,5] Output: 4
Example 3:
Input: piles = [9,8,7,6,5,1,2,3,4] Output: 18
My idea (If anyone has more elegent solution, you are welcome to leave comments here)
- Sort the piles O(nLog(n))
- Bob must can get piles.count / 3 coins.
- So the first piles.count / 3 coins (in sorted array) must belong to Bob.
- Since index start from 0, for me, I will first take the coin at piles.count / 3.
- Then for the rest of coins, no matter what strategy I use, Alice alwasys get the largest.
- So my strategy is: during each turn, giving her the largest number && I take the relatively smaller one, repeat it until all coins are assigned.
- The strategy in Step 6 also means we take coins one by one from index piles.count / 3 in the sorted array until Alice takes the largest number in the array.
- Return the result.
对这一堆硬币排序排序O(nLog(n))
鲍勃一定能得到piles.count / 3枚硬币。
前piles.count / 3枚最小的硬币必须属于Bob(他总是拿最小的)。
由于index/指数从0开始,对于我,我将从第piles.count / 3枚开始拿。
剩下的硬币,不管我用什么策略,爱丽丝总是得到最大的。
所以我的策略是:在每个回合中,给她最大的数字,而我取相对较小的数字,重复这个过程直到所有的硬币都分配好。
第六步的策略也意味着我们从索引堆中,从第piles.count / 3枚开始,我和爱丽丝一个接一个地取出硬币。直到Alice取到数组中最大的数(也就是最后一个)。
返回结果。
func maxCoins(_ piles: [Int]) -> Int {
let sortedP = piles.sorted()
let numberOfBob = sortedP.count / 3
var result = 0
var index = numberOfBob
while index <= sortedP.count - 2{
result += sortedP[index]
index += 2
}
return result
}