Skip to content

Latest commit

 

History

History
34 lines (31 loc) · 907 Bytes

948.bag-of-tokens.md

File metadata and controls

34 lines (31 loc) · 907 Bytes

Greedy

There are two greedy strategies:

  • We must gain the score with the minimum tokens. (The minimum cost)
  • We must exchange the score with the maximum power. (The maximum profit)

Based on those strategies, we can sort the tokens and use two pointers to solve the problem.

fun bagOfTokensScore(tokens: IntArray, initPower: Int): Int {
    tokens.sort()
    var power = initPower
    var score = 0
    var up = 0
    var down = token.size - 1
    var maxScore = 0
    while (up <= down) {
        if (tokens[up] <= power) {
            power -= tokens[up]
            score++
            maxScore = maxOf(maxScore, score)
            up++
        } else if (score > 0) {
            power += tokens[down]
            score--
            down--
        } else {
            break
        }
    }
    return maxScore
}