close

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

這題是指能量200,能量夠的話就花令牌能量並得分(score++),否則取令牌能量並扣分,且不重複使用令牌

tokens[0] =100<能量200,能量勝剩100,得一分,左邊移動(left++)

tokens[1] =200>能量100,從最右側取能量剩500,扣一分,右邊移動(right--)

class Solution {
    public int bagOfTokensScore(int[] tokens, int power) {
        Arrays.sort(tokens);
        int left = 0, right = tokens.length - 1;
        int points = 0, score = 0;
        /*while (left <= right && (power >= tokens[left] || points > 0)) {
            while (left <= right && power >= tokens[left]) {
                power -= tokens[left++];
                points++;
            }

            score = Math.max(score, points);
            if (left <= right && points > 0) {
                power += tokens[right--];
                points--;
            }
        }*/
       while (left <= right) {
            if (power >= tokens[left]) {
                power -= tokens[left++];
                score = Math.max(score, ++points);
            } else if (points > 0) {
                points--;
                power += tokens[right--];
            } else {
                break;
            }
        }
        return score;
    }
}

arrow
arrow
    全站熱搜

    程式小試身手 發表在 痞客邦 留言(0) 人氣()