Need help with Minimax problem!

Revision en1, by aakarshmadhavan, 2018-06-29 05:53:48

I am just trying to make a recursive solution for this but it is failing horribly. Here is the problem:

https://leetcode.com/problems/can-i-win/description/

In the "100 game," two players take turns adding, to a running total, any integer from 1..10. The player who first causes the running total to reach or exceed 100 wins.

What if we change the game so that players cannot re-use integers?

For example, two players might take turns drawing from a common pool of numbers of 1..15 without replacement until they reach a total >= 100.

Given an integer maxChoosableInteger and another integer desiredTotal, determine if the first player to move can force a win, assuming both players play optimally.

You can always assume that maxChoosableInteger will not be larger than 20 and desiredTotal will not be larger than 300.

Here is my code so far:

class Solution {
    boolean [] used;
    int total = 0;
    int maxChoosableInteger = 0;
    
    public boolean canIWin(int maxChoosableInteger, int desiredTotal) {
        used = new boolean[maxChoosableInteger + 1];
        this.total = desiredTotal;
        this.maxChoosableInteger = maxChoosableInteger;
        int n = helper(true, total);
        System.out.println(n);
        return  n >= total;
    }
    
    public int helper(boolean turn, int sum){
        if(sum < total || sum >= 2*total) return 0;
        int cur = 0;
        if(!turn) cur = Integer.MAX_VALUE;
        for(int i = maxChoosableInteger; i >= 1; --i){
            if(used[i]) continue;
            used[i] = true;
            if(turn) cur = Math.max(cur, i + helper(false, sum + i));
            else cur = Math.min(cur, -i + helper(true, sum - i));
            used[i] = false;
        }
        return cur;
    }
}

It is not working for case maxChooseableInteger=4, desiredTotal=6. If you can help me that would be very much appreciated. I am struggling with these types of "minimax" problems. Thanks in advance.

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English aakarshmadhavan 2018-06-29 05:53:48 2060 Initial revision (published)