Viscu的刷题日记

LeetCode 948.令牌放置

2019-02-03  本文已影响8人  ostreamBaba

题意

LeetCode 948.令牌放置

解法

本题采用的是贪心算法。
具体贪法是:
令牌点数小的话,我们就利用能量来换取分数;令牌点数大的话,我们就利用分数来换取能量。
限制的话:
如果我们能量一直足够的话,就一直换取分数。
如果我们能量不够的话:

代码

public class _948 {
    static class Solution {
        public static int bagOfTokensScore(int[] tokens, int P) {
            if(tokens == null || tokens.length <= 0 || P <= 0){
                return 0;
            }
            int head = 0;
            int tail = tokens.length - 1;
            Arrays.sort(tokens);
            int res = 0;
            while (head <= tail){
                if(P >= tokens[head]){
                    P -= tokens[head++];
                    ++res;
                }else if(res > 0 && (tail - head >= 2 || (P + tokens[tail]) >= 2*tokens[head])){
                    P += tokens[tail--];
                    --res;
                }else {
                    break;
                }
            }
            return res;
        }
      }   
}
上一篇 下一篇

猜你喜欢

热点阅读