【贪心】B027_令牌放置(排序 + 策略)

一、题目描述

You have an initial power P, an initial score of 0 points, and a bag of tokens.

Each token can be used at most once, has a value token[i], and has potentially two ways to use it.

  • If we have at least token[i] power, we may play the token face up, losing token[i] power, and gaining 1 point.
  • If we have at least 1 point, we may play the token face down, gaining token[i] power, and losing 1 point.

Return the largest number of points we can have after playing any number of tokens.

Input: tokens = [100,200,300,400], P = 200
Output: 2

二、题解

方法一:排序 + 策略

编码错误,思想正确:

  • 这里有 2 个点需要注意:
    • P < tokens[l] 而且 P <= 0 时,即连具有最少能量的令牌都不能翻反来获取能量的情况下,游戏是需要结束的。
    • 在使用任意数量的令牌后,返回我们可以得到的最大分数,即不需要全都使用把令牌一遍,所以需要记录翻的时候的 score 的最大值。
public int bagOfTokensScore(int[] tokens, int P) {
    Arrays.sort(tokens);
    int score = 0;
    int l = 0, r = tokens.length-1;
    while (l <= r) {
        if (P >= tokens[l]) {
            P -= tokens[l++];
            score++;
        } else {
            P += tokens[r--];
            score--;
        }
    }
    return score;
}
  • 如果我有足够的能量,我肯定是先把能量小的翻正,尽量拿分 score++
  • 否则,将能量最大的令牌翻转,因为这样会失去一分,但我也要拿到足够多的能量,为下次的得分做铺垫。
public int bagOfTokensScore(int[] tokens, int P) {
    Arrays.sort(tokens);
    int score = 0, max = 0;
    int l = 0, r = tokens.length-1;
    
    while (l <= r) {
        if (P >= tokens[l]) {
            P -= tokens[l++];
            score++;
        } else {
            if (score == 0) {
                return max;
            }
            P += tokens[r--];
            score--;
        }
        max = Math.max(max, score);
    }
    return max;
}

复杂度分析

  • 时间复杂度: O ( n l o g n ) O(nlogn)
  • 空间复杂度: O ( 1 ) O(1)
发布了691 篇原创文章 · 获赞 151 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_43539599/article/details/105416034