DEV Community

Cover image for Maximizing Score with Tokens - 948 - Bag of Tokens in Go
Mohammed Nadeem Shareef
Mohammed Nadeem Shareef

Posted on • Updated on

Maximizing Score with Tokens - 948 - Bag of Tokens in Go

Introduction

Welcome to the second post of my "Journey into GoLang" series! In this series, I'll document my GoLang programming exploration by solving LeetCode problems. Today, we are solving the 948 - Bag of Tokens problem.

The Problem Description:

You start with an initial power of power, an initial score of 0, and a bag of tokens given as an integer array tokens, where each tokens[i] donates the value of tokeni.

Your goal is to maximize the total score by strategically playing these tokens. In one move, you can play an unplayed token in one of the two ways (but not both for the same token):

Face-up: If your current power is at least tokens[i], you may play token, losing tokens[i] power and gaining 1 score.
Face-down: If your current score is at least 1, you may play token, gaining tokens[i] power and losing 1 score.

Return the maximum possible score you can achieve after playing any number of tokens.

Example:
Let's consider an example to understand the problem better:
Input:
tokens = [200, 100]
power = 150
Output:
1

LeetCode Link

Approach:

To solve this problem efficiently. We'll sort the tokens array to prioritize playing tokens with lower values first. Then, we'll iterate through the tokens array, playing tokens face-up if possible, and face-down if necessary. We'll keep track of the maximum score achieved throughout the process.

import (
    "fmt"
    "sort"
)

func bagOfTokensScore(tokens []int, power int) int {
    sort.Ints(tokens)
    left, right, score := 0, len(tokens)-1, 0
    maxScore := 0
    for left <= right {
        if power >= tokens[left] {
            power -= tokens[left]
            left++
            score++
            if score > maxScore {
                maxScore = score
            }
        } else if score > 0 {
            power += tokens[right]
            right--
            score--
        } else {
            break
        }
    }

    return maxScore
}

func main() {
    fmt.Println(bagOfTokensScore([]int{200, 100}, 150)) // Output: 1
}
Enter fullscreen mode Exit fullscreen mode

Github Code

Thank you for joining me on this journey, and I look forward to sharing more discoveries with you in the upcoming posts!

Social Links

Top comments (0)