Sunday, November 25, 2018

948. Bag of Tokens


Version #1 Greedy
Buy at the cheapest and sell at the most expensive

Time O(nlogn)

class Solution {
    public int bagOfTokensScore(int[] tokens, int P) {
        Arrays.sort(tokens);
        int left = 0;
        int point = 0;
        int max = 0;
        for (int right = tokens.length - 1; right >= left; right--) {
            while (left <= right && P >= tokens[left]) {
                P -= tokens[left++];
                point++;
            }
            max = Math.max(max, point);
            if (point > 0) {
                P += tokens[right];
                point--;
            }
        }
        return max;
    }
}

No comments:

Post a Comment