Program to count number of ways to win at most k consecutive games in Python

We need to find the number of ways to play n games such that we never win more than k consecutive games. Each game can result in a win (W) or loss (L), and we must ensure no sequence of k+1 consecutive wins occurs.

For example, if n = 3 and k = 2, the valid sequences are: "LLL", "WLL", "LWL", "LLW", "WWL", "LWW", "WLW" (7 ways total).

Approach

We'll use dynamic programming with memoization. The key insight is to track the current position in the game sequence and the number of consecutive wins so far ?

Algorithm Steps

  • Define a recursive function dp(i, consecutive_wins) where i is the current game position and consecutive_wins tracks current consecutive wins
  • Base case: if we've played all n games and never exceeded k consecutive wins, return 1
  • If consecutive wins exceed k, return 0 (invalid sequence)
  • For each position, we can either win (increment consecutive wins) or lose (reset consecutive wins to 0)

Implementation

def solve(n, k):
    MOD = 10**9 + 7
    memo = {}
    
    def dp(i, consecutive_wins):
        # Base case: completed all games
        if i == n:
            return 1
        
        # Invalid case: too many consecutive wins
        if consecutive_wins > k:
            return 0
            
        # Check memoization
        if (i, consecutive_wins) in memo:
            return memo[(i, consecutive_wins)]
        
        # Option 1: Lose current game (reset consecutive wins)
        lose = dp(i + 1, 0) % MOD
        
        # Option 2: Win current game (increment consecutive wins)
        win = dp(i + 1, consecutive_wins + 1) % MOD
        
        result = (lose + win) % MOD
        memo[(i, consecutive_wins)] = result
        return result
    
    return dp(0, 0)

# Test cases
n, k = 3, 2
print(f"n={n}, k={k}: {solve(n, k)} ways")

n, k = 4, 2  
print(f"n={n}, k={k}: {solve(n, k)} ways")
n=3, k=2: 7 ways
n=4, k=2: 13 ways

How It Works

The algorithm explores all possible game sequences:

  • State representation: (current_position, consecutive_wins_so_far)
  • Transitions: At each game, choose to win or lose
  • Constraint: Never allow consecutive_wins to exceed k
  • Memoization: Cache results to avoid recomputing the same states

Time Complexity

The time complexity is O(n × k) since we have at most n × (k+1) unique states, and each state is computed once due to memoization.

Conclusion

This dynamic programming solution efficiently counts valid game sequences by tracking consecutive wins and using memoization to avoid redundant calculations. The approach ensures we never exceed k consecutive wins while exploring all possible win/loss combinations.

Updated on: 2026-03-26T17:01:00+05:30

366 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements