publicintpirateCoinAllocation(int n, int k){ /* n pirates split the k gold coin, from index 0 to index n-1, decide the allocation , if over half of the pirates agree, then do it, else kill the one, and next. Get the max number of gold coin the index 0 can get and also survive.Note that one pirate vote death unless it can make him get more coins. */
Queue<Integer> queue = new PriorityQueue<>(); queue.offer(k); int ret = 0; System.out.println(queue); for (int i = 2; i <= n; i++) { int needVoteCnt = i / 2; int curSum = 0; List<Integer> set = new ArrayList<>(); if (needVoteCnt > queue.size()) { queue.offer(0); continue; } for (int j = 0; j < needVoteCnt; j++) { curSum += queue.peek() + 1; set.add(queue.poll()); } if (curSum > k) { for (int c : set) { queue.offer(c); } queue.offer(0); } else { queue.clear(); for (int j = 0; j < i - 1 - needVoteCnt; j++) { queue.offer(0); } for (int c : set) { queue.offer(c + 1); } queue.offer(k - curSum); ret = k - curSum; } System.out.printf("cur number of pirates: %d, allocation: %s\n", i, queue); } return ret; }