leetcode- 948. 令牌放置

目标是让分数最大

package com;

import java.util.Arrays;
import java.util.Scanner;

public class Main {
	@SuppressWarnings("resource")
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		Solution s = new Solution();
		int T;
		T = scan.nextInt();
		while (T-- != 0) {
			int n = scan.nextInt();
			int[] A = new int[n];
			for (int i = 0; i < n; ++i)
				A[i] = scan.nextInt();

			int res = s.bagOfTokensScore(A, 150);
			System.out.println(res);
		}
	}
}

class Solution {
	public int bagOfTokensScore(int[] tokens, int P) {
		int l = 0, r = tokens.length - 1, res = 0;
		if (l == r) {
			if (P >= tokens[0])
				return 1;
			else
				return 0;
		}
		Arrays.sort(tokens);
		while (l < r) {
			while (P >= tokens[l]) {
				P -= tokens[l];
				++res;
				++l;
			}
			if (l < r) {
				P += tokens[r];
				--res;
				--r;
			}
		}
		return res >= 0 ? res : 0;
	}
}

 

你可能感兴趣的:(leetcode- 948. 令牌放置)