什么是贪心
贪心的本质是选择每一阶段的局部最优,从而达到全局最优。
这么说有点抽象,来举一个例子:
例如,有一堆钞票,你可以拿走十张,如果想达到最大的金额,你要怎么拿?
指定每次拿最大的,最终结果就是拿走最大数额的钱。
每次拿最大的就是局部最优,最后拿走最大数额的钱就是推出全局最优。
来实践一下:
https://leetcode-cn.com/problems/longest-happy-string/
public String longestDiverseString(int a, int b, int c) {
PriorityQueue<int []> heap = new PriorityQueue<>(new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o2[1]-o1[1];
}
});
if (a>0){
heap.offer(new int[]{'a',a});
}
if (b>0) {
heap.offer(new int[]{'b',b});
}
if (c>0) {
heap.offer(new int[]{'c',c});
}
StringBuilder sb = new StringBuilder(a + b + c);
while (!heap.isEmpty()) {
int [] top = heap.poll();
int n = sb.length();
if (n>=2 && sb.charAt(n-1) ==top[0] && sb.charAt(n-2) == top[0]) {
if (!heap.isEmpty()) {
int[] second = heap.poll();
sb.append((char)second[0]);
if (--second[1] > 0) {
heap.offer(second);
}
heap.offer(top);
}
}else {
sb.append((char) top[0]);
if (--top[1]>0) {
heap.offer(top);
}
}
}
return sb.toString();
}