Thursday, September 3, 2020

LeetCode [1140] Stone Game II

 1140. Stone Game II

Medium

Alex and Lee continue their games with piles of stones.  There are a number of piles arranged in a row, and each pile has a positive integer number of stones piles[i].  The objective of the game is to end with the most stones. 

Alex and Lee take turns, with Alex starting first.  Initially, M = 1.

On each player's turn, that player can take all the stones in the first X remaining piles, where 1 <= X <= 2M.  Then, we set M = max(M, X).

The game continues until all the stones have been taken.

Assuming Alex and Lee play optimally, return the maximum number of stones Alex can get.

 

Example 1:

Input: piles = [2,7,9,4,4]
Output: 10
Explanation:  If Alex takes one pile at the beginning, Lee takes two piles, then Alex takes 2 piles again. Alex can get 2 + 4 + 4 = 10 piles in total. If Alex takes two piles at the beginning, then Lee can take all three piles left. In this case, Alex get 2 + 7 = 9 piles in total. So we return 10 since it's larger. 

 

Constraints:

  • 1 <= piles.length <= 100
  • 1 <= piles[i] <= 10 ^ 4
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
    int[][] memo;
    int n;
    int[] preSum;
    public int stoneGameII(int[] piles) {
        n = piles.length;
        preSum = Arrays.copyOf(piles, n);
        for(int i=n-2; i>=0; --i){
            preSum[i] += preSum[i+1];
        }
        memo = new int[n][n];//memo[i][j]: max stones when M = i in piles[j..n-1]
        return helper(1, 0);
    }

    int helper(int M, int p){
        if(p+M*2>=n) return preSum[p];//take all left
        int res = 0;
        if(memo[M][p]>0) return memo[M][p];
        for(int t=1; t<=M*2; ++t){
            int curTake = preSum[p] - preSum[p+t];
            res = Math.max(res, curTake+preSum[p+t]-helper(Math.max(M, t), p+t));
        }
        memo[M][p] = res;
        return res;
    }
}

LeetCode [877] Stone Game

 877. Stone Game

Medium

Alex and Lee play a game with piles of stones.  There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i].

The objective of the game is to end with the most stones.  The total number of stones is odd, so there are no ties.

Alex and Lee take turns, with Alex starting first.  Each turn, a player takes the entire pile of stones from either the beginning or the end of the row.  This continues until there are no more piles left, at which point the person with the most stones wins.

Assuming Alex and Lee play optimally, return True if and only if Alex wins the game.

 

Example 1:

Input: piles = [5,3,4,5]
Output: true
Explanation: 
Alex starts first, and can only take the first 5 or the last 5.
Say he takes the first 5, so that the row becomes [3, 4, 5].
If Lee takes 3, then the board is [4, 5], and Alex takes 5 to win with 10 points.
If Lee takes the last 5, then the board is [3, 4], and Alex takes 4 to win with 9 points.
This demonstrated that taking the first 5 was a winning move for Alex, so we return true.

 

Constraints:

  • 2 <= piles.length <= 500
  • piles.length is even.
  • 1 <= piles[i] <= 500
  • sum(piles) is odd.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
    public boolean stoneGame(int[] piles) {
        int n = piles.length;
        int[][] dp = new int[n][n];
        for(int i=0; i<n; ++i) dp[i][i] = piles[i];
        for(int i=n-2; i>=0; --i){
            for(int j=i+1; j<n; ++j){
                dp[i][j] = Math.max(piles[i]-dp[i+1][j], piles[j]-dp[i][j-1]);
            }
        }
        return dp[0][n-1]>0;
    }
}

LeetCode [1146] Snapshot Array

 1146. Snapshot Array

Medium

Implement a SnapshotArray that supports the following interface:

  • SnapshotArray(int length) initializes an array-like data structure with the given length.  Initially, each element equals 0.
  • void set(index, val) sets the element at the given index to be equal to val.
  • int snap() takes a snapshot of the array and returns the snap_id: the total number of times we called snap() minus 1.
  • int get(index, snap_id) returns the value at the given index, at the time we took the snapshot with the given snap_id

 

Example 1:

Input: ["SnapshotArray","set","snap","set","get"]
[[3],[0,5],[],[0,6],[0,0]]
Output: [null,null,0,null,5]
Explanation: 
SnapshotArray snapshotArr = new SnapshotArray(3); // set the length to be 3
snapshotArr.set(0,5);  // Set array[0] = 5
snapshotArr.snap();  // Take a snapshot, return snap_id = 0
snapshotArr.set(0,6);
snapshotArr.get(0,0);  // Get the value of array[0] with snap_id = 0, return 5

 

Constraints:

  • 1 <= length <= 50000
  • At most 50000 calls will be made to set, snap, and get.
  • 0 <= index < length
  • 0 <= snap_id < (the total number of times we call snap())
  • 0 <= val <= 10^9
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class SnapshotArray {
    TreeMap<Integer, Integer>[] ss;
    int snap_id = 0;
    public SnapshotArray(int length) {
        ss = new TreeMap[length];
        for(int i=0; i<length; ++i)
        {
            ss[i] = new TreeMap<Integer, Integer>();
            ss[i].put(0, 0);
        }
    }
    
    public void set(int index, int val) {
        ss[index].put(snap_id, val);
    }
    
    public int snap() {
        return snap_id++;
    }
    
    public int get(int index, int snap_id) {
        return ss[index].floorEntry(snap_id).getValue();
    }
    public static void main(String[] args) {
        System.out.println("Hi");
    }
}

/**
 * Your SnapshotArray object will be instantiated and called as such:
 * SnapshotArray obj = new SnapshotArray(length);
 * obj.set(index,val);
 * int param_2 = obj.snap();
 * int param_3 = obj.get(index,snap_id);
 */

LeetCode [1145] Binary Tree Coloring Game

 1145. Binary Tree Coloring Game

Medium

Two players play a turn based game on a binary tree.  We are given the root of this binary tree, and the number of nodes n in the tree.  n is odd, and each node has a distinct value from 1 to n.

Initially, the first player names a value x with 1 <= x <= n, and the second player names a value y with 1 <= y <= n and y != x.  The first player colors the node with value x red, and the second player colors the node with value y blue.

Then, the players take turns starting with the first player.  In each turn, that player chooses a node of their color (red if player 1, blue if player 2) and colors an uncolored neighbor of the chosen node (either the left child, right child, or parent of the chosen node.)

If (and only if) a player cannot choose such a node in this way, they must pass their turn.  If both players pass their turn, the game ends, and the winner is the player that colored more nodes.

You are the second player.  If it is possible to choose such a y to ensure you win the game, return true.  If it is not possible, return false.

 

Example 1:

Input: root = [1,2,3,4,5,6,7,8,9,10,11], n = 11, x = 3
Output: true
Explanation: The second player can choose the node with value 2.

 

Constraints:

  • root is the root of a binary tree with n nodes and distinct node values from 1 to n.
  • n is odd.
  • 1 <= x <= n <= 100
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    int left = 0, right = 0, val = 0;
    public boolean btreeGameWinningMove(TreeNode root, int n, int x) {
        val = x;
        count(root);
        int player2 = Math.max(Math.max(left, right), n-left-right-1);
        return player2>n/2;
    }
    
    int count(TreeNode root){
        if(root==null) return 0;
        int l = count(root.left);
        int r = count(root.right);
        if(root.val==val){
            left = l;
            right = r;
        }
        return l+r+1;
    }
}

LeetCode [1153] String Transforms Into Another String

 1153. String Transforms Into Another String

Hard

Given two strings str1 and str2 of the same length, determine whether you can transform str1 into str2 by doing zero or more conversions.

In one conversion you can convert all occurrences of one character in str1 to any other lowercase English character.

Return true if and only if you can transform str1 into str2.

 

Example 1:

Input: str1 = "aabcc", str2 = "ccdee"
Output: true
Explanation: Convert 'c' to 'e' then 'b' to 'd' then 'a' to 'c'. Note that the order of conversions matter.

Example 2:

Input: str1 = "leetcode", str2 = "codeleet"
Output: false
Explanation: There is no way to transform str1 to str2.

 

Note:

  1. 1 <= str1.length == str2.length <= 10^4
  2. Both str1 and str2 contain only lowercase English letters.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
    public boolean canConvert(String str1, String str2) {
        if(str1.equals(str2)) return true;
        Map<Character, Character> map = new HashMap<>();
        for(int i=0; i<str1.length(); ++i){
            char c1 = str1.charAt(i), c2 = str2.charAt(i);
            if(map.containsKey(c1) && map.get(c1)!=c2) return false;
            map.put(c1, c2);
        }
        return new HashSet<Character>(map.values()).size() < 26;
    }
}


@thyang93

I would recommend putting two words in two columns vertically, something like this,

s1="ace", s2="cea", draw arrows between each transformation
key  -> value
a    ->    c
c    ->    e
e    ->    a

If a value shows up later as a key, then it makes a linkedlist structure,
and if a value has already been a key, then there is a cycle (in this case, the last "a" is the key in the first row).

For linkedlist without cycle we can just backward substitute the key with the value, there exists a way of converting s1 to s2 for sure.

    eg., ace -> ceb: a-(1)->c-(2)->e-(3)->b. 

            We do 3, 2, 1 conversions. ace->acb->aeb->ceb 

However, with a cycle, any conversion would conflict with an existing char.
For linkedlist with a cycle, such as "a -> c -> e -> a", we need to break the loop and use a temporary variable to cache the point of break,
in this case, it becomes the transformation with two steps: "a -> tmp" and "tmp -> c -> e -> a".

Then we can do ace->tce->tca->tea->cea
Now the bottleneck is if we can find a temporary variable to carry the conversion, if there is one, then the conversion is viable.

LeetCode [1170] Compare Strings by Frequency of the Smallest Character

 1170. Compare Strings by Frequency of the Smallest Character

Easy

Let's define a function f(s) over a non-empty string s, which calculates the frequency of the smallest character in s. For example, if s = "dcce" then f(s) = 2 because the smallest character is "c" and its frequency is 2.

Now, given string arrays queries and words, return an integer array answer, where each answer[i] is the number of words such that f(queries[i]) < f(W), where W is a word in words.

 

Example 1:

Input: queries = ["cbd"], words = ["zaaaz"]
Output: [1]
Explanation: On the first query we have f("cbd") = 1, f("zaaaz") = 3 so f("cbd") < f("zaaaz").

Example 2:

Input: queries = ["bbb","cc"], words = ["a","aa","aaa","aaaa"]
Output: [1,2]
Explanation: On the first query only f("bbb") < f("aaaa"). On the second query both f("aaa") and f("aaaa") are both > f("cc").

 

Constraints:

  • 1 <= queries.length <= 2000
  • 1 <= words.length <= 2000
  • 1 <= queries[i].length, words[i].length <= 10
  • queries[i][j], words[i][j] are English lowercase letters.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Solution {
    int getFreq(String word)
    {
        int[] freq = new int[26];
        for(char c:word.toCharArray())
        {
            freq[c-'a']++;
        }
        for(int i=0; i<26; ++i)
        {
            if(freq[i]!=0)
                return freq[i];
        }
        return 0;
    }

    public int[] numSmallerByFrequency(String[] queries, String[] words) {
        int[] qF = new int[queries.length];
        for(int i=0; i<queries.length; ++i) qF[i] = getFreq(queries[i]);
        int[] wF = new int[words.length];
        for(int i=0; i<words.length; ++i) wF[i] = getFreq(words[i]);
        Arrays.sort(wF);

        int[] ret = new int[queries.length];
        for(int i=0; i<queries.length; ++i){
            int l = 0, r = wF.length-1;

            //find l as the first one with wF[l]>qF[i];
            //l will also be the lenth of words whose frequence<=qF[i]
            while(l<=r)
            {
                int m = l + (r-l)/2;
                if(wF[m]<=qF[i])
                {
                    l = m+1;
                }else{
                    r = m-1;
                }
            }
            ret[i] = words.length - l;
        }
        return ret;
    }
}