title
stringlengths
1
100
titleSlug
stringlengths
3
77
Java
int64
0
1
Python3
int64
1
1
content
stringlengths
28
44.4k
voteCount
int64
0
3.67k
question_content
stringlengths
65
5k
question_hints
stringclasses
970 values
Python3: Recursive Dict Approach
split-a-string-into-the-max-number-of-unique-substrings
0
1
# Intuition\nUsing a dictionary to keep track of used substrings\n\n# Approach\n- index: The current index in the string \'s\'. It determines the starting point for creating substrings at each level of recursion.\n- cur: A dictionary to keep track of the current substrings that have been encountered.\n```\ndef recursive(index, cur):\n```\nBase case: If we have traversed the entire string \'s\', update the result if the current set of substrings is larger.\n```\nif index == n:\n cur_len = len(cur)\n\n if cur_len > result:\n result = cur_len\n```\nRecursive exploration: Cut the string \'s\' from \'index\' to \'j\', inclusive. If the substring is already in our dictionary, skip this iteration. Otherwise, append the substring to the dictionary and proceed to the next level of recursion with \'j\' + 1 and the \'cur\' dictionary. After that, remove \'tmp\' from the dictionary to create a bigger substring for the next iteration.\n```\nfor j in range(index, n):\n tmp = s[index:j + 1]\n\n if tmp in cur:\n continue\n\n cur[tmp] = True\n recursive(j + 1, cur)\n del cur[tmp]\n```\n\n# Complexity\n- Time complexity:\n$$O(2^N)$$\n\n- Space complexity:\n$$O(N)$$\n\n# Code\n```\nclass Solution:\n def maxUniqueSplit(self, s: str) -> int:\n def recursive(index, cur):\n nonlocal result\n \n if index == n:\n cur_len = len(cur)\n\n if cur_len > result:\n result = cur_len\n\n for j in range(index, n):\n tmp = s[index:j + 1]\n\n if tmp in cur:\n continue\n\n cur[tmp] = True\n recursive(j + 1, cur)\n del cur[tmp]\n\n n = len(s)\n result = 0\n recursive(0, {})\n\n return result\n \n```
0
Given a string `s`, return _the maximum number of unique substrings that the given string can be split into_. You can split string `s` into any list of **non-empty substrings**, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are **unique**. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** s = "ababccc " **Output:** 5 **Explanation**: One way to split maximally is \['a', 'b', 'ab', 'c', 'cc'\]. Splitting like \['a', 'b', 'a', 'b', 'c', 'cc'\] is not valid as you have 'a' and 'b' multiple times. **Example 2:** **Input:** s = "aba " **Output:** 2 **Explanation**: One way to split maximally is \['a', 'ba'\]. **Example 3:** **Input:** s = "aa " **Output:** 1 **Explanation**: It is impossible to split the string any further. **Constraints:** * `1 <= s.length <= 16` * `s` contains only lower case English letters.
null
Concise solution on python3
split-a-string-into-the-max-number-of-unique-substrings
0
1
\n# Code\n```\nclass Solution:\n def maxUniqueSplit(self, s: str) -> int:\n \n def go(start, used):\n if start == len(s):\n return len(used)\n\n cur = ""\n ans = 0\n for i in range(start, len(s)):\n cur = cur + s[i]\n if cur in used:\n continue\n used.add(cur)\n ans = max(ans, go(i+1, used))\n used.remove(cur)\n\n return ans\n\n\n return go(0, set())\n \n```
0
Given a string `s`, return _the maximum number of unique substrings that the given string can be split into_. You can split string `s` into any list of **non-empty substrings**, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are **unique**. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** s = "ababccc " **Output:** 5 **Explanation**: One way to split maximally is \['a', 'b', 'ab', 'c', 'cc'\]. Splitting like \['a', 'b', 'a', 'b', 'c', 'cc'\] is not valid as you have 'a' and 'b' multiple times. **Example 2:** **Input:** s = "aba " **Output:** 2 **Explanation**: One way to split maximally is \['a', 'ba'\]. **Example 3:** **Input:** s = "aa " **Output:** 1 **Explanation**: It is impossible to split the string any further. **Constraints:** * `1 <= s.length <= 16` * `s` contains only lower case English letters.
null
Python Bit Mask, Easy to Understand
split-a-string-into-the-max-number-of-unique-substrings
0
1
# Intuition\nWhen overcoming questions like this, think about DP. If DP fails, then no choice we need to bruteforce\n\n# Approach\nHow to make array of permutation:\nThink about divider as 1 and no divider as 0\nabba -> a [] b | b [] a, divider = [no, divide, no]\nabba -> a | b [] b | a, divider = [divide, no, divide ]\n\nOk, now we see if we have 4 elements, we have 3 dividers that we need to switch off or on. We can do bitmask to permute this\n\nuse python: [format(i, f\'0{n}b\') for i in range(2**n)]\n\nthen for every permutation we just need to check if it is valid or not. (by checking for repetition), then we find the permutation that gives us the max answer. VOILAA\n\n# Complexity\n- Time complexity: $$O(2^n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nSince string is max length at 16, we can assume traversing through string to check if it is valid or not = O(1)\n- Space complexity: $$O(2^n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nto store the permutation\n\n# Code\n```\nclass Solution:\n \n def maxUniqueSplit(self, s: str) -> int:\n def generate_bit_masks(n):\n return [format(i, f\'0{n}b\') for i in range(2**n)]\n def countones(s):\n count = 0\n for i in s:\n if i == "1":\n count += 1\n return count\n\n n = len(s)\n ans = -float(\'inf\')\n perm = generate_bit_masks(n-1)\n # print(perm)\n for i in range(len(perm)):\n mask = perm[i]\n mySet = set()\n trackChar = s[0]\n is_working = True\n for j in range(len(mask)):\n currChar = s[j+1]\n #handle corner case\n if j == len(mask)-1:\n to_input = ""\n if mask[j] == "0":\n s1 = trackChar + currChar\n if s1 in mySet:\n is_working= False\n break\n else:\n s1 = trackChar\n s2 = currChar\n if s1 in mySet:\n is_working= False\n break\n mySet.add(s1)\n if s2 in mySet:\n is_working= False\n break\n break\n\n\n # if no divider, then append\n if mask[j] == "0":\n trackChar += currChar\n else:\n # check if trackChar is in set\n if trackChar in mySet:\n #if yes, we are fked. This mask does not work.\n is_working = False\n break\n else:\n mySet.add(trackChar)\n trackChar = s[j+1]\n if is_working:\n print(mask, mySet)\n ans = max(ans, 1 + countones(mask))\n\n\n return ans\n\n \n```
0
Given a string `s`, return _the maximum number of unique substrings that the given string can be split into_. You can split string `s` into any list of **non-empty substrings**, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are **unique**. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** s = "ababccc " **Output:** 5 **Explanation**: One way to split maximally is \['a', 'b', 'ab', 'c', 'cc'\]. Splitting like \['a', 'b', 'a', 'b', 'c', 'cc'\] is not valid as you have 'a' and 'b' multiple times. **Example 2:** **Input:** s = "aba " **Output:** 2 **Explanation**: One way to split maximally is \['a', 'ba'\]. **Example 3:** **Input:** s = "aa " **Output:** 1 **Explanation**: It is impossible to split the string any further. **Constraints:** * `1 <= s.length <= 16` * `s` contains only lower case English letters.
null
Recursion | Used Dictionary
split-a-string-into-the-max-number-of-unique-substrings
0
1
\n\n# Code\n```\nclass Solution:\n def maxUniqueSplit(self, s: str) -> int:\n self.count = 0\n self.counter = {}\n\n def solve(s, cnt):\n if s == "":\n self.count = max(self.count, cnt)\n return\n\n for i in range(len(s)):\n if s[:i+1] not in self.counter:\n self.counter[s[:i+1]] = 1\n solve(s[i+1:], cnt+1)\n del self.counter[s[:i+1]]\n \n return\n\n solve(s, 0)\n return self.count\n \n\n\n \n \n```
0
Given a string `s`, return _the maximum number of unique substrings that the given string can be split into_. You can split string `s` into any list of **non-empty substrings**, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are **unique**. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** s = "ababccc " **Output:** 5 **Explanation**: One way to split maximally is \['a', 'b', 'ab', 'c', 'cc'\]. Splitting like \['a', 'b', 'a', 'b', 'c', 'cc'\] is not valid as you have 'a' and 'b' multiple times. **Example 2:** **Input:** s = "aba " **Output:** 2 **Explanation**: One way to split maximally is \['a', 'ba'\]. **Example 3:** **Input:** s = "aa " **Output:** 1 **Explanation**: It is impossible to split the string any further. **Constraints:** * `1 <= s.length <= 16` * `s` contains only lower case English letters.
null
Python3 + Backtracking
split-a-string-into-the-max-number-of-unique-substrings
0
1
# Code\n```\nclass Solution:\n def maxUniqueSplit(self, s: str) -> int:\n unique = set()\n curr = []\n max_len = 1\n\n def backtrack(i):\n nonlocal max_len\n if i == len(s):\n if len(curr) > 1:\n max_len = max(max_len,len(curr))\n return\n for k in range(i, len(s)):\n sub = s[i:k + 1]\n if sub not in unique:\n curr.append(sub)\n unique.add(sub)\n backtrack(k + 1)\n unique.remove(sub)\n curr.pop()\n\n backtrack(0)\n return max_len \n\n \n```
0
Given a string `s`, return _the maximum number of unique substrings that the given string can be split into_. You can split string `s` into any list of **non-empty substrings**, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are **unique**. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** s = "ababccc " **Output:** 5 **Explanation**: One way to split maximally is \['a', 'b', 'ab', 'c', 'cc'\]. Splitting like \['a', 'b', 'a', 'b', 'c', 'cc'\] is not valid as you have 'a' and 'b' multiple times. **Example 2:** **Input:** s = "aba " **Output:** 2 **Explanation**: One way to split maximally is \['a', 'ba'\]. **Example 3:** **Input:** s = "aa " **Output:** 1 **Explanation**: It is impossible to split the string any further. **Constraints:** * `1 <= s.length <= 16` * `s` contains only lower case English letters.
null
Easy Python Solution
split-a-string-into-the-max-number-of-unique-substrings
0
1
# Code\n```\nclass Solution:\n def maxUniqueSplit(self, s: str) -> int:\n unique_set=set()\n count=0\n ans=0\n def backtrack(start, count):\n nonlocal ans\n if start==len(s):\n ans= max(ans, count)\n for end in range(start+1, len(s)+1):\n substring=s[start:end]\n if substring not in unique_set:\n unique_set.add(substring)\n backtrack(end, count+1)\n unique_set.remove(substring)\n return ans\n backtrack(0,count)\n return ans\n\n```
0
Given a string `s`, return _the maximum number of unique substrings that the given string can be split into_. You can split string `s` into any list of **non-empty substrings**, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are **unique**. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** s = "ababccc " **Output:** 5 **Explanation**: One way to split maximally is \['a', 'b', 'ab', 'c', 'cc'\]. Splitting like \['a', 'b', 'a', 'b', 'c', 'cc'\] is not valid as you have 'a' and 'b' multiple times. **Example 2:** **Input:** s = "aba " **Output:** 2 **Explanation**: One way to split maximally is \['a', 'ba'\]. **Example 3:** **Input:** s = "aa " **Output:** 1 **Explanation**: It is impossible to split the string any further. **Constraints:** * `1 <= s.length <= 16` * `s` contains only lower case English letters.
null
[Python3] Simple Backtracking
split-a-string-into-the-max-number-of-unique-substrings
0
1
# Code\n```\nclass Solution:\n def maxUniqueSplit(self, s: str) -> int:\n self.hs = set()\n def helper(cur):\n if cur >= len(s):\n return 0\n ret = 0\n for i in range(cur+1, len(s)+1):\n if s[cur: i] not in self.hs:\n self.hs.add(s[cur: i])\n ret = max(ret, helper(i) + 1) \n self.hs.remove(s[cur: i])\n return ret\n\n return helper(0)\n```
0
Given a string `s`, return _the maximum number of unique substrings that the given string can be split into_. You can split string `s` into any list of **non-empty substrings**, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are **unique**. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** s = "ababccc " **Output:** 5 **Explanation**: One way to split maximally is \['a', 'b', 'ab', 'c', 'cc'\]. Splitting like \['a', 'b', 'a', 'b', 'c', 'cc'\] is not valid as you have 'a' and 'b' multiple times. **Example 2:** **Input:** s = "aba " **Output:** 2 **Explanation**: One way to split maximally is \['a', 'ba'\]. **Example 3:** **Input:** s = "aa " **Output:** 1 **Explanation**: It is impossible to split the string any further. **Constraints:** * `1 <= s.length <= 16` * `s` contains only lower case English letters.
null
Python (Simple Backtracking)
split-a-string-into-the-max-number-of-unique-substrings
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxUniqueSplit(self, s):\n n = len(s)\n\n def backtrack(s,path):\n if not s:\n res.append(path)\n\n for i in range(1,len(s)+1):\n if s[:i] not in path:\n backtrack(s[i:],path+[s[:i]])\n\n res = []\n backtrack(s,[])\n return max([len(i) for i in res])\n\n\n \n \n \n \n \n```
0
Given a string `s`, return _the maximum number of unique substrings that the given string can be split into_. You can split string `s` into any list of **non-empty substrings**, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are **unique**. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** s = "ababccc " **Output:** 5 **Explanation**: One way to split maximally is \['a', 'b', 'ab', 'c', 'cc'\]. Splitting like \['a', 'b', 'a', 'b', 'c', 'cc'\] is not valid as you have 'a' and 'b' multiple times. **Example 2:** **Input:** s = "aba " **Output:** 2 **Explanation**: One way to split maximally is \['a', 'ba'\]. **Example 3:** **Input:** s = "aa " **Output:** 1 **Explanation**: It is impossible to split the string any further. **Constraints:** * `1 <= s.length <= 16` * `s` contains only lower case English letters.
null
Typical backtracking problem | clear code | full explanation
split-a-string-into-the-max-number-of-unique-substrings
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n1. Use a set to keep track of which substrings have been used already.\n2. Try each possible substring at every position and backtrack if a complete split is not possible.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Define a helper function to do backtracking with three param `i` which is the position that we want to test out all the possible substring. `count` is the local count of number of substrings that currently splited. `visited` is a set used to check if the current substring is used already.\n2. When `i==len(s)` we already reach the end of the string so we update the `ans`, otherwise, we try out all possible substring starting at index `i` to `j` and skip all visited substring. For the non-visited one, we take it and do backtracking.\n3. return the final `ans`\n# Complexity\n- Time complexity: O(n^2) where `n` is the size of `s`\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n^2) since the set is similar structure as a dictionary\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxUniqueSplit(self, s: str) -> int:\n ans = 0\n def helper(i, count, visited):\n nonlocal ans\n if i == len(s):\n # update the ans\n ans = max(ans, count)\n else:\n for j in range(i + 1, len(s) + 1):\n if s[i:j] in visited:\n continue\n else:\n # backtracking\n visited.add(s[i:j])\n helper(j, count + 1, visited)\n visited.remove(s[i:j])\n helper(0, 0, set())\n return ans\n```
0
Given a string `s`, return _the maximum number of unique substrings that the given string can be split into_. You can split string `s` into any list of **non-empty substrings**, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are **unique**. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** s = "ababccc " **Output:** 5 **Explanation**: One way to split maximally is \['a', 'b', 'ab', 'c', 'cc'\]. Splitting like \['a', 'b', 'a', 'b', 'c', 'cc'\] is not valid as you have 'a' and 'b' multiple times. **Example 2:** **Input:** s = "aba " **Output:** 2 **Explanation**: One way to split maximally is \['a', 'ba'\]. **Example 3:** **Input:** s = "aa " **Output:** 1 **Explanation**: It is impossible to split the string any further. **Constraints:** * `1 <= s.length <= 16` * `s` contains only lower case English letters.
null
[Python3] top-down dp
maximum-non-negative-product-in-a-matrix
0
1
\n```\nclass Solution:\n def maxProductPath(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n \n @lru_cache(None)\n def fn(i, j): \n """Return maximum & minimum products ending at (i, j)."""\n if i == 0 and j == 0: return grid[0][0], grid[0][0]\n if i < 0 or j < 0: return -inf, inf\n if grid[i][j] == 0: return 0, 0\n mx1, mn1 = fn(i-1, j) # from top\n mx2, mn2 = fn(i, j-1) # from left \n mx, mn = max(mx1, mx2)*grid[i][j], min(mn1, mn2)*grid[i][j]\n return (mx, mn) if grid[i][j] > 0 else (mn, mx)\n \n mx, _ = fn(m-1, n-1)\n return -1 if mx < 0 else mx % 1_000_000_007\n```
39
You are given a `m x n` matrix `grid`. Initially, you are located at the top-left corner `(0, 0)`, and in each step, you can only **move right or down** in the matrix. Among all possible paths starting from the top-left corner `(0, 0)` and ending in the bottom-right corner `(m - 1, n - 1)`, find the path with the **maximum non-negative product**. The product of a path is the product of all integers in the grid cells visited along the path. Return the _maximum non-negative product **modulo**_ `109 + 7`. _If the maximum product is **negative**, return_ `-1`. Notice that the modulo is performed after getting the maximum product. **Example 1:** **Input:** grid = \[\[-1,-2,-3\],\[-2,-3,-3\],\[-3,-3,-2\]\] **Output:** -1 **Explanation:** It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1. **Example 2:** **Input:** grid = \[\[1,-2,1\],\[1,-2,1\],\[3,-4,1\]\] **Output:** 8 **Explanation:** Maximum non-negative product is shown (1 \* 1 \* -2 \* -4 \* 1 = 8). **Example 3:** **Input:** grid = \[\[1,3\],\[0,-4\]\] **Output:** 0 **Explanation:** Maximum non-negative product is shown (1 \* 0 \* -4 = 0). **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 15` * `-4 <= grid[i][j] <= 4`
null
[Python3] top-down dp
maximum-non-negative-product-in-a-matrix
0
1
\n```\nclass Solution:\n def maxProductPath(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n \n @lru_cache(None)\n def fn(i, j): \n """Return maximum & minimum products ending at (i, j)."""\n if i == 0 and j == 0: return grid[0][0], grid[0][0]\n if i < 0 or j < 0: return -inf, inf\n if grid[i][j] == 0: return 0, 0\n mx1, mn1 = fn(i-1, j) # from top\n mx2, mn2 = fn(i, j-1) # from left \n mx, mn = max(mx1, mx2)*grid[i][j], min(mn1, mn2)*grid[i][j]\n return (mx, mn) if grid[i][j] > 0 else (mn, mx)\n \n mx, _ = fn(m-1, n-1)\n return -1 if mx < 0 else mx % 1_000_000_007\n```
39
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put in `$1` more than the day before. On every subsequent Monday, he will put in `$1` more than the **previous Monday**. Given `n`, return _the total amount of money he will have in the Leetcode bank at the end of the_ `nth` _day._ **Example 1:** **Input:** n = 4 **Output:** 10 **Explanation:** After the 4th day, the total is 1 + 2 + 3 + 4 = 10. **Example 2:** **Input:** n = 10 **Output:** 37 **Explanation:** After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2. **Example 3:** **Input:** n = 20 **Output:** 96 **Explanation:** After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96. **Constraints:** * `1 <= n <= 1000`
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
[Python3] Bottom-up Dynamic Programming
maximum-non-negative-product-in-a-matrix
0
1
### Intuition\nTypical bottom-up solution\n\n### Complexity\n`time`: `O(M * N)`\n`space`: `O(M * N)`\t\t\n### Solution\n```python\ndef maxProductPath(self, A: List[List[int]]) -> int:\n\tm, n = len(A), len(A[0])\n\tMax = [[0] * n for _ in range(m)]\n\tMin = [[0] * n for _ in range(m)]\n\tMax[0][0] = A[0][0]\n\tMin[0][0] = A[0][0]\n\tfor j in range(1, n):\n\t\tMax[0][j] = Max[0][j - 1] * A[0][j]\n\t\tMin[0][j] = Min[0][j - 1] * A[0][j]\n\n\tfor i in range(1, m):\n\t\tMax[i][0] = Max[i - 1][0] * A[i][0]\n\t\tMin[i][0] = Min[i - 1][0] * A[i][0]\n\tfor i in range(1, m):\n\t\tfor j in range(1, n):\n\t\t\tif A[i][j] > 0:\n\t\t\t\tMax[i][j] = max(Max[i - 1][j], Max[i][j - 1]) * A[i][j]\n\t\t\t\tMin[i][j] = min(Min[i - 1][j], Min[i][j - 1]) * A[i][j]\n\t\t\telse:\n\t\t\t\tMax[i][j] = min(Min[i - 1][j], Min[i][j - 1]) * A[i][j]\n\t\t\t\tMin[i][j] = max(Max[i - 1][j], Max[i][j - 1]) * A[i][j]\n\treturn Max[-1][-1] % int(1e9 + 7) if Max[-1][-1] >= 0 else -1\n```
16
You are given a `m x n` matrix `grid`. Initially, you are located at the top-left corner `(0, 0)`, and in each step, you can only **move right or down** in the matrix. Among all possible paths starting from the top-left corner `(0, 0)` and ending in the bottom-right corner `(m - 1, n - 1)`, find the path with the **maximum non-negative product**. The product of a path is the product of all integers in the grid cells visited along the path. Return the _maximum non-negative product **modulo**_ `109 + 7`. _If the maximum product is **negative**, return_ `-1`. Notice that the modulo is performed after getting the maximum product. **Example 1:** **Input:** grid = \[\[-1,-2,-3\],\[-2,-3,-3\],\[-3,-3,-2\]\] **Output:** -1 **Explanation:** It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1. **Example 2:** **Input:** grid = \[\[1,-2,1\],\[1,-2,1\],\[3,-4,1\]\] **Output:** 8 **Explanation:** Maximum non-negative product is shown (1 \* 1 \* -2 \* -4 \* 1 = 8). **Example 3:** **Input:** grid = \[\[1,3\],\[0,-4\]\] **Output:** 0 **Explanation:** Maximum non-negative product is shown (1 \* 0 \* -4 = 0). **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 15` * `-4 <= grid[i][j] <= 4`
null
[Python3] Bottom-up Dynamic Programming
maximum-non-negative-product-in-a-matrix
0
1
### Intuition\nTypical bottom-up solution\n\n### Complexity\n`time`: `O(M * N)`\n`space`: `O(M * N)`\t\t\n### Solution\n```python\ndef maxProductPath(self, A: List[List[int]]) -> int:\n\tm, n = len(A), len(A[0])\n\tMax = [[0] * n for _ in range(m)]\n\tMin = [[0] * n for _ in range(m)]\n\tMax[0][0] = A[0][0]\n\tMin[0][0] = A[0][0]\n\tfor j in range(1, n):\n\t\tMax[0][j] = Max[0][j - 1] * A[0][j]\n\t\tMin[0][j] = Min[0][j - 1] * A[0][j]\n\n\tfor i in range(1, m):\n\t\tMax[i][0] = Max[i - 1][0] * A[i][0]\n\t\tMin[i][0] = Min[i - 1][0] * A[i][0]\n\tfor i in range(1, m):\n\t\tfor j in range(1, n):\n\t\t\tif A[i][j] > 0:\n\t\t\t\tMax[i][j] = max(Max[i - 1][j], Max[i][j - 1]) * A[i][j]\n\t\t\t\tMin[i][j] = min(Min[i - 1][j], Min[i][j - 1]) * A[i][j]\n\t\t\telse:\n\t\t\t\tMax[i][j] = min(Min[i - 1][j], Min[i][j - 1]) * A[i][j]\n\t\t\t\tMin[i][j] = max(Max[i - 1][j], Max[i][j - 1]) * A[i][j]\n\treturn Max[-1][-1] % int(1e9 + 7) if Max[-1][-1] >= 0 else -1\n```
16
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put in `$1` more than the day before. On every subsequent Monday, he will put in `$1` more than the **previous Monday**. Given `n`, return _the total amount of money he will have in the Leetcode bank at the end of the_ `nth` _day._ **Example 1:** **Input:** n = 4 **Output:** 10 **Explanation:** After the 4th day, the total is 1 + 2 + 3 + 4 = 10. **Example 2:** **Input:** n = 10 **Output:** 37 **Explanation:** After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2. **Example 3:** **Input:** n = 20 **Output:** 96 **Explanation:** After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96. **Constraints:** * `1 <= n <= 1000`
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
DFS || Dynamic Programming || Memoization || Python3
maximum-non-negative-product-in-a-matrix
0
1
```\nclass Solution:\n def maxProductPath(self, grid: List[List[int]]) -> int:\n def isBound(row,col):\n return 0<=row<len(grid) and 0<=col<len(grid[0])\n \n @lru_cache(None)\n def dfs(row,col,product):\n if not isBound(row, col):\n return -1\n if row == len(grid) - 1 and col == len(grid[0]) - 1:\n return product * grid[row][col]\n return max(dfs(row+1,col, product * grid[row][col]),dfs(row,col+1, product * grid[row][col])) \n max_product = dfs(0,0,1)\n return max_product %(10**9+7) if max_product!=-1 else -1\n \n```
2
You are given a `m x n` matrix `grid`. Initially, you are located at the top-left corner `(0, 0)`, and in each step, you can only **move right or down** in the matrix. Among all possible paths starting from the top-left corner `(0, 0)` and ending in the bottom-right corner `(m - 1, n - 1)`, find the path with the **maximum non-negative product**. The product of a path is the product of all integers in the grid cells visited along the path. Return the _maximum non-negative product **modulo**_ `109 + 7`. _If the maximum product is **negative**, return_ `-1`. Notice that the modulo is performed after getting the maximum product. **Example 1:** **Input:** grid = \[\[-1,-2,-3\],\[-2,-3,-3\],\[-3,-3,-2\]\] **Output:** -1 **Explanation:** It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1. **Example 2:** **Input:** grid = \[\[1,-2,1\],\[1,-2,1\],\[3,-4,1\]\] **Output:** 8 **Explanation:** Maximum non-negative product is shown (1 \* 1 \* -2 \* -4 \* 1 = 8). **Example 3:** **Input:** grid = \[\[1,3\],\[0,-4\]\] **Output:** 0 **Explanation:** Maximum non-negative product is shown (1 \* 0 \* -4 = 0). **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 15` * `-4 <= grid[i][j] <= 4`
null
DFS || Dynamic Programming || Memoization || Python3
maximum-non-negative-product-in-a-matrix
0
1
```\nclass Solution:\n def maxProductPath(self, grid: List[List[int]]) -> int:\n def isBound(row,col):\n return 0<=row<len(grid) and 0<=col<len(grid[0])\n \n @lru_cache(None)\n def dfs(row,col,product):\n if not isBound(row, col):\n return -1\n if row == len(grid) - 1 and col == len(grid[0]) - 1:\n return product * grid[row][col]\n return max(dfs(row+1,col, product * grid[row][col]),dfs(row,col+1, product * grid[row][col])) \n max_product = dfs(0,0,1)\n return max_product %(10**9+7) if max_product!=-1 else -1\n \n```
2
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put in `$1` more than the day before. On every subsequent Monday, he will put in `$1` more than the **previous Monday**. Given `n`, return _the total amount of money he will have in the Leetcode bank at the end of the_ `nth` _day._ **Example 1:** **Input:** n = 4 **Output:** 10 **Explanation:** After the 4th day, the total is 1 + 2 + 3 + 4 = 10. **Example 2:** **Input:** n = 10 **Output:** 37 **Explanation:** After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2. **Example 3:** **Input:** n = 20 **Output:** 96 **Explanation:** After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96. **Constraints:** * `1 <= n <= 1000`
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
Python 3 | DP O(m*n) time, In place | Explanation
maximum-non-negative-product-in-a-matrix
0
1
### Explanation\n- At each position `(i, j)`, maintain a tuple for `(small, large)`\n\t- small: smallest product up to this point\n\t- large: largest product up to this point\n- Update each point from top to bottom, from left to right. Current `small` or `large` only depends on values on the left or above.\n### Implementation\n```\nclass Solution:\n def maxProductPath(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n grid[0][0] = grid[0][0], grid[0][0] # (small, large) for starting point\n for j in range(1, n):\n grid[0][j] = grid[0][j-1][0]*grid[0][j], grid[0][j-1][1]*grid[0][j] # special handling first row\n for i in range(1, m):\n grid[i][0] = grid[i-1][0][0]*grid[i][0], grid[i-1][0][1]*grid[i][0] # special handling first col\n for i in range(1, m):\n for j in range(1, n):\n nums = [grid[i-1][j][0]*grid[i][j], grid[i][j-1][0]*grid[i][j], grid[i-1][j][1]*grid[i][j], grid[i][j-1][1]*grid[i][j]]\n small, large = min(nums), max(nums)\n grid[i][j] = (small, large) # update all other points\n return (grid[-1][-1][1] % 1000000007) if grid[-1][-1][1] >= 0 else -1\n```
6
You are given a `m x n` matrix `grid`. Initially, you are located at the top-left corner `(0, 0)`, and in each step, you can only **move right or down** in the matrix. Among all possible paths starting from the top-left corner `(0, 0)` and ending in the bottom-right corner `(m - 1, n - 1)`, find the path with the **maximum non-negative product**. The product of a path is the product of all integers in the grid cells visited along the path. Return the _maximum non-negative product **modulo**_ `109 + 7`. _If the maximum product is **negative**, return_ `-1`. Notice that the modulo is performed after getting the maximum product. **Example 1:** **Input:** grid = \[\[-1,-2,-3\],\[-2,-3,-3\],\[-3,-3,-2\]\] **Output:** -1 **Explanation:** It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1. **Example 2:** **Input:** grid = \[\[1,-2,1\],\[1,-2,1\],\[3,-4,1\]\] **Output:** 8 **Explanation:** Maximum non-negative product is shown (1 \* 1 \* -2 \* -4 \* 1 = 8). **Example 3:** **Input:** grid = \[\[1,3\],\[0,-4\]\] **Output:** 0 **Explanation:** Maximum non-negative product is shown (1 \* 0 \* -4 = 0). **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 15` * `-4 <= grid[i][j] <= 4`
null
Python 3 | DP O(m*n) time, In place | Explanation
maximum-non-negative-product-in-a-matrix
0
1
### Explanation\n- At each position `(i, j)`, maintain a tuple for `(small, large)`\n\t- small: smallest product up to this point\n\t- large: largest product up to this point\n- Update each point from top to bottom, from left to right. Current `small` or `large` only depends on values on the left or above.\n### Implementation\n```\nclass Solution:\n def maxProductPath(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n grid[0][0] = grid[0][0], grid[0][0] # (small, large) for starting point\n for j in range(1, n):\n grid[0][j] = grid[0][j-1][0]*grid[0][j], grid[0][j-1][1]*grid[0][j] # special handling first row\n for i in range(1, m):\n grid[i][0] = grid[i-1][0][0]*grid[i][0], grid[i-1][0][1]*grid[i][0] # special handling first col\n for i in range(1, m):\n for j in range(1, n):\n nums = [grid[i-1][j][0]*grid[i][j], grid[i][j-1][0]*grid[i][j], grid[i-1][j][1]*grid[i][j], grid[i][j-1][1]*grid[i][j]]\n small, large = min(nums), max(nums)\n grid[i][j] = (small, large) # update all other points\n return (grid[-1][-1][1] % 1000000007) if grid[-1][-1][1] >= 0 else -1\n```
6
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put in `$1` more than the day before. On every subsequent Monday, he will put in `$1` more than the **previous Monday**. Given `n`, return _the total amount of money he will have in the Leetcode bank at the end of the_ `nth` _day._ **Example 1:** **Input:** n = 4 **Output:** 10 **Explanation:** After the 4th day, the total is 1 + 2 + 3 + 4 = 10. **Example 2:** **Input:** n = 10 **Output:** 37 **Explanation:** After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2. **Example 3:** **Input:** n = 20 **Output:** 96 **Explanation:** After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96. **Constraints:** * `1 <= n <= 1000`
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
Bottom Up Dp Solution
maximum-non-negative-product-in-a-matrix
0
1
```\nclass Solution:\n \n # O(n*m) time,\n # O(n*m) space,\n # Approach: bottom up dp, greedy\n def maxProductPath(self, grid: List[List[int]]) -> int:\n \n \'\'\'\n the key take here is to store the smallest negative number and largest positive value at each cell,\n then when we can make the smallest negative number a large positive number when multiplied by any negative number which we might return as the maximum positive value\n \n \'\'\'\n \n MOD = 10**9 + 7\n rows, cols = len(grid), len(grid[0])\n dp = [[[-1, -1] for _ in range(cols)] for _ in range(rows)]\n \n dp[-1][-1][0] = grid[-1][-1]\n dp[-1][-1][1] = grid[-1][-1]\n \n for row in range(rows-1, -1, -1):\n for col in range(cols-1, -1, -1):\n if (row, col) == (rows-1, cols-1):\n continue\n \n max_pos = float(\'-inf\')\n min_neg = float(\'inf\')\n # downwards\n if row + 1 < rows:\n max_pos = dp[row+1][col][0]\n min_neg = dp[row+1][col][1]\n \n # right\n if col + 1 < cols:\n max_pos = max(max_pos, dp[row][col+1][0])\n min_neg = min(min_neg, dp[row][col+1][1])\n \n curr_val = grid[row][col]\n if curr_val >= 0:\n dp[row][col][0] = max_pos*curr_val\n dp[row][col][1] = min_neg*curr_val\n else:\n dp[row][col][0] = min_neg*curr_val\n dp[row][col][1] = max_pos*curr_val\n\n sign = -1 if dp[0][0][0] < 0 else 1\n ans = abs(dp[0][0][0] if dp[0][0][0] >= 0 else -1) % MOD\n return ans * sign\n```
0
You are given a `m x n` matrix `grid`. Initially, you are located at the top-left corner `(0, 0)`, and in each step, you can only **move right or down** in the matrix. Among all possible paths starting from the top-left corner `(0, 0)` and ending in the bottom-right corner `(m - 1, n - 1)`, find the path with the **maximum non-negative product**. The product of a path is the product of all integers in the grid cells visited along the path. Return the _maximum non-negative product **modulo**_ `109 + 7`. _If the maximum product is **negative**, return_ `-1`. Notice that the modulo is performed after getting the maximum product. **Example 1:** **Input:** grid = \[\[-1,-2,-3\],\[-2,-3,-3\],\[-3,-3,-2\]\] **Output:** -1 **Explanation:** It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1. **Example 2:** **Input:** grid = \[\[1,-2,1\],\[1,-2,1\],\[3,-4,1\]\] **Output:** 8 **Explanation:** Maximum non-negative product is shown (1 \* 1 \* -2 \* -4 \* 1 = 8). **Example 3:** **Input:** grid = \[\[1,3\],\[0,-4\]\] **Output:** 0 **Explanation:** Maximum non-negative product is shown (1 \* 0 \* -4 = 0). **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 15` * `-4 <= grid[i][j] <= 4`
null
Bottom Up Dp Solution
maximum-non-negative-product-in-a-matrix
0
1
```\nclass Solution:\n \n # O(n*m) time,\n # O(n*m) space,\n # Approach: bottom up dp, greedy\n def maxProductPath(self, grid: List[List[int]]) -> int:\n \n \'\'\'\n the key take here is to store the smallest negative number and largest positive value at each cell,\n then when we can make the smallest negative number a large positive number when multiplied by any negative number which we might return as the maximum positive value\n \n \'\'\'\n \n MOD = 10**9 + 7\n rows, cols = len(grid), len(grid[0])\n dp = [[[-1, -1] for _ in range(cols)] for _ in range(rows)]\n \n dp[-1][-1][0] = grid[-1][-1]\n dp[-1][-1][1] = grid[-1][-1]\n \n for row in range(rows-1, -1, -1):\n for col in range(cols-1, -1, -1):\n if (row, col) == (rows-1, cols-1):\n continue\n \n max_pos = float(\'-inf\')\n min_neg = float(\'inf\')\n # downwards\n if row + 1 < rows:\n max_pos = dp[row+1][col][0]\n min_neg = dp[row+1][col][1]\n \n # right\n if col + 1 < cols:\n max_pos = max(max_pos, dp[row][col+1][0])\n min_neg = min(min_neg, dp[row][col+1][1])\n \n curr_val = grid[row][col]\n if curr_val >= 0:\n dp[row][col][0] = max_pos*curr_val\n dp[row][col][1] = min_neg*curr_val\n else:\n dp[row][col][0] = min_neg*curr_val\n dp[row][col][1] = max_pos*curr_val\n\n sign = -1 if dp[0][0][0] < 0 else 1\n ans = abs(dp[0][0][0] if dp[0][0][0] >= 0 else -1) % MOD\n return ans * sign\n```
0
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put in `$1` more than the day before. On every subsequent Monday, he will put in `$1` more than the **previous Monday**. Given `n`, return _the total amount of money he will have in the Leetcode bank at the end of the_ `nth` _day._ **Example 1:** **Input:** n = 4 **Output:** 10 **Explanation:** After the 4th day, the total is 1 + 2 + 3 + 4 = 10. **Example 2:** **Input:** n = 10 **Output:** 37 **Explanation:** After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2. **Example 3:** **Input:** n = 20 **Output:** 96 **Explanation:** After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96. **Constraints:** * `1 <= n <= 1000`
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
python3 solution for bp
maximum-non-negative-product-in-a-matrix
0
1
# Code\n```\nclass Solution:\n def maxProductPath(self, grid: List[List[int]]) -> int:\n m = len(grid)\n n = len(grid[0])\n dp = [[[float(\'inf\'), -float(\'inf\')] for _ in range(n)] for _ in range(m)]\n dp[0][0] = [grid[0][0], grid[0][0]]\n for i in range(m):\n for j in range(n):\n if i >= 1:\n dp[i][j][0], dp[i][j][1] = min(dp[i-1][j][0]*grid[i][j], dp[i-1][j][1]*grid[i][j]), max(dp[i-1][j][0]*grid[i][j], dp[i-1][j][1]*grid[i][j])\n if j >= 1:\n dp[i][j][0], dp[i][j][1] = min(dp[i][j][0], dp[i][j-1][0]*grid[i][j], dp[i][j-1][1]*grid[i][j]), max(dp[i][j][1], dp[i][j-1][0]*grid[i][j], dp[i][j-1][1]*grid[i][j])\n \n return dp[-1][-1][1] % (10**9 + 7) if dp[-1][-1][1] >= 0 else -1\n\n \n```
0
You are given a `m x n` matrix `grid`. Initially, you are located at the top-left corner `(0, 0)`, and in each step, you can only **move right or down** in the matrix. Among all possible paths starting from the top-left corner `(0, 0)` and ending in the bottom-right corner `(m - 1, n - 1)`, find the path with the **maximum non-negative product**. The product of a path is the product of all integers in the grid cells visited along the path. Return the _maximum non-negative product **modulo**_ `109 + 7`. _If the maximum product is **negative**, return_ `-1`. Notice that the modulo is performed after getting the maximum product. **Example 1:** **Input:** grid = \[\[-1,-2,-3\],\[-2,-3,-3\],\[-3,-3,-2\]\] **Output:** -1 **Explanation:** It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1. **Example 2:** **Input:** grid = \[\[1,-2,1\],\[1,-2,1\],\[3,-4,1\]\] **Output:** 8 **Explanation:** Maximum non-negative product is shown (1 \* 1 \* -2 \* -4 \* 1 = 8). **Example 3:** **Input:** grid = \[\[1,3\],\[0,-4\]\] **Output:** 0 **Explanation:** Maximum non-negative product is shown (1 \* 0 \* -4 = 0). **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 15` * `-4 <= grid[i][j] <= 4`
null
python3 solution for bp
maximum-non-negative-product-in-a-matrix
0
1
# Code\n```\nclass Solution:\n def maxProductPath(self, grid: List[List[int]]) -> int:\n m = len(grid)\n n = len(grid[0])\n dp = [[[float(\'inf\'), -float(\'inf\')] for _ in range(n)] for _ in range(m)]\n dp[0][0] = [grid[0][0], grid[0][0]]\n for i in range(m):\n for j in range(n):\n if i >= 1:\n dp[i][j][0], dp[i][j][1] = min(dp[i-1][j][0]*grid[i][j], dp[i-1][j][1]*grid[i][j]), max(dp[i-1][j][0]*grid[i][j], dp[i-1][j][1]*grid[i][j])\n if j >= 1:\n dp[i][j][0], dp[i][j][1] = min(dp[i][j][0], dp[i][j-1][0]*grid[i][j], dp[i][j-1][1]*grid[i][j]), max(dp[i][j][1], dp[i][j-1][0]*grid[i][j], dp[i][j-1][1]*grid[i][j])\n \n return dp[-1][-1][1] % (10**9 + 7) if dp[-1][-1][1] >= 0 else -1\n\n \n```
0
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put in `$1` more than the day before. On every subsequent Monday, he will put in `$1` more than the **previous Monday**. Given `n`, return _the total amount of money he will have in the Leetcode bank at the end of the_ `nth` _day._ **Example 1:** **Input:** n = 4 **Output:** 10 **Explanation:** After the 4th day, the total is 1 + 2 + 3 + 4 = 10. **Example 2:** **Input:** n = 10 **Output:** 37 **Explanation:** After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2. **Example 3:** **Input:** n = 20 **Output:** 96 **Explanation:** After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96. **Constraints:** * `1 <= n <= 1000`
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
[Python 3] Top Down DP
maximum-non-negative-product-in-a-matrix
0
1
# Intuition\nSimilar to Maximum Product Subarray problem\n\n\n# Complexity\n- Time complexity:\n O(m*n)\n- Space complexity:\n O(m*n) but can be optimized to O(n) by keeping track of only previous row and current row\n\n# Code\n```\nclass Solution:\n def maxProductPath(self, grid: List[List[int]]) -> int:\n m,n = len(grid), len(grid[0])\n dp = [[0]*n for _ in range(m)]\n\n dp[0][0] = (grid[0][0],grid[0][0])\n for i in range(1,n):\n dp[0][i] = (dp[0][i-1][0]*grid[0][i], dp[0][i-1][1]*grid[0][i])\n for i in range(1,m):\n dp[i][0] = (dp[i-1][0][0]*grid[i][0], dp[i-1][0][1]*grid[i][0])\n\n for i in range(1,m):\n for j in range(1,n):\n v = grid[i][j]\n a = max(dp[i-1][j][0]*v,dp[i-1][j][1]*v,dp[i][j-1][0]*v,dp[i][j-1][1]*v)\n b = min(dp[i-1][j][0]*v,dp[i-1][j][1]*v,dp[i][j-1][0]*v,dp[i][j-1][1]*v) \n dp[i][j] = (a,b) \n \n if dp[-1][-1][0]<0:\n return -1\n return dp[-1][-1][0]%(1000000007)\n \n \n```
0
You are given a `m x n` matrix `grid`. Initially, you are located at the top-left corner `(0, 0)`, and in each step, you can only **move right or down** in the matrix. Among all possible paths starting from the top-left corner `(0, 0)` and ending in the bottom-right corner `(m - 1, n - 1)`, find the path with the **maximum non-negative product**. The product of a path is the product of all integers in the grid cells visited along the path. Return the _maximum non-negative product **modulo**_ `109 + 7`. _If the maximum product is **negative**, return_ `-1`. Notice that the modulo is performed after getting the maximum product. **Example 1:** **Input:** grid = \[\[-1,-2,-3\],\[-2,-3,-3\],\[-3,-3,-2\]\] **Output:** -1 **Explanation:** It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1. **Example 2:** **Input:** grid = \[\[1,-2,1\],\[1,-2,1\],\[3,-4,1\]\] **Output:** 8 **Explanation:** Maximum non-negative product is shown (1 \* 1 \* -2 \* -4 \* 1 = 8). **Example 3:** **Input:** grid = \[\[1,3\],\[0,-4\]\] **Output:** 0 **Explanation:** Maximum non-negative product is shown (1 \* 0 \* -4 = 0). **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 15` * `-4 <= grid[i][j] <= 4`
null
[Python 3] Top Down DP
maximum-non-negative-product-in-a-matrix
0
1
# Intuition\nSimilar to Maximum Product Subarray problem\n\n\n# Complexity\n- Time complexity:\n O(m*n)\n- Space complexity:\n O(m*n) but can be optimized to O(n) by keeping track of only previous row and current row\n\n# Code\n```\nclass Solution:\n def maxProductPath(self, grid: List[List[int]]) -> int:\n m,n = len(grid), len(grid[0])\n dp = [[0]*n for _ in range(m)]\n\n dp[0][0] = (grid[0][0],grid[0][0])\n for i in range(1,n):\n dp[0][i] = (dp[0][i-1][0]*grid[0][i], dp[0][i-1][1]*grid[0][i])\n for i in range(1,m):\n dp[i][0] = (dp[i-1][0][0]*grid[i][0], dp[i-1][0][1]*grid[i][0])\n\n for i in range(1,m):\n for j in range(1,n):\n v = grid[i][j]\n a = max(dp[i-1][j][0]*v,dp[i-1][j][1]*v,dp[i][j-1][0]*v,dp[i][j-1][1]*v)\n b = min(dp[i-1][j][0]*v,dp[i-1][j][1]*v,dp[i][j-1][0]*v,dp[i][j-1][1]*v) \n dp[i][j] = (a,b) \n \n if dp[-1][-1][0]<0:\n return -1\n return dp[-1][-1][0]%(1000000007)\n \n \n```
0
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put in `$1` more than the day before. On every subsequent Monday, he will put in `$1` more than the **previous Monday**. Given `n`, return _the total amount of money he will have in the Leetcode bank at the end of the_ `nth` _day._ **Example 1:** **Input:** n = 4 **Output:** 10 **Explanation:** After the 4th day, the total is 1 + 2 + 3 + 4 = 10. **Example 2:** **Input:** n = 10 **Output:** 37 **Explanation:** After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2. **Example 3:** **Input:** n = 20 **Output:** 96 **Explanation:** After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96. **Constraints:** * `1 <= n <= 1000`
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
Python - typical bottom up DP
maximum-non-negative-product-in-a-matrix
0
1
# Complexity\n- Time complexity:\n$$O(n)$$ - n is number of cells in grid\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution:\n def maxProductPath(self, g: List[List[int]]) -> int:\n R, C, mod = len(g), len(g[0]), 1_000_000_007\n dp = [[[inf, -inf] for _ in range(C)] for _ in range(R)]\n dp[0][0] = [g[0][0], g[0][0]]\n for r in range(R):\n for c in range(C):\n if (r, c) == (0, 0): continue\n v = g[r][c]\n if c > 0:\n smaller, bigger = v * dp[r][c - 1][0], v * dp[r][c - 1][1]\n dp[r][c][0] = min(dp[r][c][0], smaller, bigger)\n dp[r][c][1] = max(dp[r][c][1], smaller, bigger)\n if r > 0:\n smaller, bigger = v * dp[r - 1][c][0], v * dp[r - 1][c][1]\n dp[r][c][0] = min(dp[r][c][0], smaller, bigger)\n dp[r][c][1] = max(dp[r][c][1], smaller, bigger) \n return dp[-1][-1][1] % mod if dp[-1][-1][1] >= 0 else -1\n```
0
You are given a `m x n` matrix `grid`. Initially, you are located at the top-left corner `(0, 0)`, and in each step, you can only **move right or down** in the matrix. Among all possible paths starting from the top-left corner `(0, 0)` and ending in the bottom-right corner `(m - 1, n - 1)`, find the path with the **maximum non-negative product**. The product of a path is the product of all integers in the grid cells visited along the path. Return the _maximum non-negative product **modulo**_ `109 + 7`. _If the maximum product is **negative**, return_ `-1`. Notice that the modulo is performed after getting the maximum product. **Example 1:** **Input:** grid = \[\[-1,-2,-3\],\[-2,-3,-3\],\[-3,-3,-2\]\] **Output:** -1 **Explanation:** It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1. **Example 2:** **Input:** grid = \[\[1,-2,1\],\[1,-2,1\],\[3,-4,1\]\] **Output:** 8 **Explanation:** Maximum non-negative product is shown (1 \* 1 \* -2 \* -4 \* 1 = 8). **Example 3:** **Input:** grid = \[\[1,3\],\[0,-4\]\] **Output:** 0 **Explanation:** Maximum non-negative product is shown (1 \* 0 \* -4 = 0). **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 15` * `-4 <= grid[i][j] <= 4`
null
Python - typical bottom up DP
maximum-non-negative-product-in-a-matrix
0
1
# Complexity\n- Time complexity:\n$$O(n)$$ - n is number of cells in grid\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution:\n def maxProductPath(self, g: List[List[int]]) -> int:\n R, C, mod = len(g), len(g[0]), 1_000_000_007\n dp = [[[inf, -inf] for _ in range(C)] for _ in range(R)]\n dp[0][0] = [g[0][0], g[0][0]]\n for r in range(R):\n for c in range(C):\n if (r, c) == (0, 0): continue\n v = g[r][c]\n if c > 0:\n smaller, bigger = v * dp[r][c - 1][0], v * dp[r][c - 1][1]\n dp[r][c][0] = min(dp[r][c][0], smaller, bigger)\n dp[r][c][1] = max(dp[r][c][1], smaller, bigger)\n if r > 0:\n smaller, bigger = v * dp[r - 1][c][0], v * dp[r - 1][c][1]\n dp[r][c][0] = min(dp[r][c][0], smaller, bigger)\n dp[r][c][1] = max(dp[r][c][1], smaller, bigger) \n return dp[-1][-1][1] % mod if dp[-1][-1][1] >= 0 else -1\n```
0
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put in `$1` more than the day before. On every subsequent Monday, he will put in `$1` more than the **previous Monday**. Given `n`, return _the total amount of money he will have in the Leetcode bank at the end of the_ `nth` _day._ **Example 1:** **Input:** n = 4 **Output:** 10 **Explanation:** After the 4th day, the total is 1 + 2 + 3 + 4 = 10. **Example 2:** **Input:** n = 10 **Output:** 37 **Explanation:** After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2. **Example 3:** **Input:** n = 20 **Output:** 96 **Explanation:** After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96. **Constraints:** * `1 <= n <= 1000`
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
[Python3] Simple Top Down Two Method Approach
maximum-non-negative-product-in-a-matrix
0
1
# Code\n```\nclass Solution:\n def maxProductPath(self, grid: List[List[int]]) -> int:\n \n m = len(grid)\n n = len(grid[0])\n\n @cache\n def dpPositive(r,c): # returns the largest positive product path from r,c\n if not (0<=r<m and 0<=c<n):\n return -1\n if (r,c) == (m-1, n-1):\n if grid[-1][-1] >= 0:\n return grid[-1][-1]\n return -1\n \n if grid[r][c] == 0:\n return 0\n\n if grid[r][c] > 0:\n return grid[r][c] * max(dpPositive(r+1,c), dpPositive(r,c+1))\n if grid[r][c] < 0:\n return grid[r][c] * min(dpNegative(r+1, c), dpNegative(r,c+1))\n\n @cache\n def dpNegative(r,c):\n if not (0<=r<m and 0<=c<n):\n return 1\n if (r,c) == (m-1, n-1):\n if grid[-1][-1] <=0:\n return grid[-1][-1]\n return 1\n \n if grid[r][c] == 0:\n return 0\n\n if grid[r][c] > 0:\n return grid[r][c] * min(dpNegative(r+1,c), dpNegative(r,c+1))\n if grid[r][c] < 0:\n return grid[r][c] * max(dpPositive(r+1, c), dpPositive(r,c+1))\n\n\n\n \n if dpPositive(0,0) >= 0:\n return dpPositive(0,0) % (10**9 + 7)\n return -1\n\n \n \n\n```
0
You are given a `m x n` matrix `grid`. Initially, you are located at the top-left corner `(0, 0)`, and in each step, you can only **move right or down** in the matrix. Among all possible paths starting from the top-left corner `(0, 0)` and ending in the bottom-right corner `(m - 1, n - 1)`, find the path with the **maximum non-negative product**. The product of a path is the product of all integers in the grid cells visited along the path. Return the _maximum non-negative product **modulo**_ `109 + 7`. _If the maximum product is **negative**, return_ `-1`. Notice that the modulo is performed after getting the maximum product. **Example 1:** **Input:** grid = \[\[-1,-2,-3\],\[-2,-3,-3\],\[-3,-3,-2\]\] **Output:** -1 **Explanation:** It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1. **Example 2:** **Input:** grid = \[\[1,-2,1\],\[1,-2,1\],\[3,-4,1\]\] **Output:** 8 **Explanation:** Maximum non-negative product is shown (1 \* 1 \* -2 \* -4 \* 1 = 8). **Example 3:** **Input:** grid = \[\[1,3\],\[0,-4\]\] **Output:** 0 **Explanation:** Maximum non-negative product is shown (1 \* 0 \* -4 = 0). **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 15` * `-4 <= grid[i][j] <= 4`
null
[Python3] Simple Top Down Two Method Approach
maximum-non-negative-product-in-a-matrix
0
1
# Code\n```\nclass Solution:\n def maxProductPath(self, grid: List[List[int]]) -> int:\n \n m = len(grid)\n n = len(grid[0])\n\n @cache\n def dpPositive(r,c): # returns the largest positive product path from r,c\n if not (0<=r<m and 0<=c<n):\n return -1\n if (r,c) == (m-1, n-1):\n if grid[-1][-1] >= 0:\n return grid[-1][-1]\n return -1\n \n if grid[r][c] == 0:\n return 0\n\n if grid[r][c] > 0:\n return grid[r][c] * max(dpPositive(r+1,c), dpPositive(r,c+1))\n if grid[r][c] < 0:\n return grid[r][c] * min(dpNegative(r+1, c), dpNegative(r,c+1))\n\n @cache\n def dpNegative(r,c):\n if not (0<=r<m and 0<=c<n):\n return 1\n if (r,c) == (m-1, n-1):\n if grid[-1][-1] <=0:\n return grid[-1][-1]\n return 1\n \n if grid[r][c] == 0:\n return 0\n\n if grid[r][c] > 0:\n return grid[r][c] * min(dpNegative(r+1,c), dpNegative(r,c+1))\n if grid[r][c] < 0:\n return grid[r][c] * max(dpPositive(r+1, c), dpPositive(r,c+1))\n\n\n\n \n if dpPositive(0,0) >= 0:\n return dpPositive(0,0) % (10**9 + 7)\n return -1\n\n \n \n\n```
0
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put in `$1` more than the day before. On every subsequent Monday, he will put in `$1` more than the **previous Monday**. Given `n`, return _the total amount of money he will have in the Leetcode bank at the end of the_ `nth` _day._ **Example 1:** **Input:** n = 4 **Output:** 10 **Explanation:** After the 4th day, the total is 1 + 2 + 3 + 4 = 10. **Example 2:** **Input:** n = 10 **Output:** 37 **Explanation:** After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2. **Example 3:** **Input:** n = 20 **Output:** 96 **Explanation:** After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96. **Constraints:** * `1 <= n <= 1000`
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
Simple Python Solution
maximum-non-negative-product-in-a-matrix
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nCreate a 2D list which stores the [min, max] for every (row,col). then return the max value of bottom right.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N2)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxProductPath(self, grid: List[List[int]]) -> int:\n result = [[[float(\'inf\'), float(\'-inf\')] for _ in range(len(grid[0]))] for _ in range(len(grid))]\n result[0][0] = [grid[0][0],grid[0][0]]\n for row in range(len(grid)):\n for col in range(len(grid[0])):\n tempMin, tempMax = float(\'inf\'), float(\'-inf\')\n temp = grid[row][col]\n if col>0:\n tempMin = min(result[row][col-1][0]*temp, result[row][col-1][1]*temp)\n tempMax = max(result[row][col-1][0]*temp, result[row][col-1][1]*temp)\n\n if row > 0:\n tempMin = min(result[row-1][col][0]*temp, result[row-1][col][1]*temp, tempMin)\n tempMax = max(result[row-1][col][0]*temp, result[row-1][col][1]*temp, tempMax)\n if row != 0 or col != 0:\n result[row][col] = [tempMin, tempMax]\n\n return -1 if max(result[-1][-1]) < 0 else max(result[-1][-1]) % (pow(10,9)+7)\n\n\n```
0
You are given a `m x n` matrix `grid`. Initially, you are located at the top-left corner `(0, 0)`, and in each step, you can only **move right or down** in the matrix. Among all possible paths starting from the top-left corner `(0, 0)` and ending in the bottom-right corner `(m - 1, n - 1)`, find the path with the **maximum non-negative product**. The product of a path is the product of all integers in the grid cells visited along the path. Return the _maximum non-negative product **modulo**_ `109 + 7`. _If the maximum product is **negative**, return_ `-1`. Notice that the modulo is performed after getting the maximum product. **Example 1:** **Input:** grid = \[\[-1,-2,-3\],\[-2,-3,-3\],\[-3,-3,-2\]\] **Output:** -1 **Explanation:** It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1. **Example 2:** **Input:** grid = \[\[1,-2,1\],\[1,-2,1\],\[3,-4,1\]\] **Output:** 8 **Explanation:** Maximum non-negative product is shown (1 \* 1 \* -2 \* -4 \* 1 = 8). **Example 3:** **Input:** grid = \[\[1,3\],\[0,-4\]\] **Output:** 0 **Explanation:** Maximum non-negative product is shown (1 \* 0 \* -4 = 0). **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 15` * `-4 <= grid[i][j] <= 4`
null
Simple Python Solution
maximum-non-negative-product-in-a-matrix
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nCreate a 2D list which stores the [min, max] for every (row,col). then return the max value of bottom right.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N2)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxProductPath(self, grid: List[List[int]]) -> int:\n result = [[[float(\'inf\'), float(\'-inf\')] for _ in range(len(grid[0]))] for _ in range(len(grid))]\n result[0][0] = [grid[0][0],grid[0][0]]\n for row in range(len(grid)):\n for col in range(len(grid[0])):\n tempMin, tempMax = float(\'inf\'), float(\'-inf\')\n temp = grid[row][col]\n if col>0:\n tempMin = min(result[row][col-1][0]*temp, result[row][col-1][1]*temp)\n tempMax = max(result[row][col-1][0]*temp, result[row][col-1][1]*temp)\n\n if row > 0:\n tempMin = min(result[row-1][col][0]*temp, result[row-1][col][1]*temp, tempMin)\n tempMax = max(result[row-1][col][0]*temp, result[row-1][col][1]*temp, tempMax)\n if row != 0 or col != 0:\n result[row][col] = [tempMin, tempMax]\n\n return -1 if max(result[-1][-1]) < 0 else max(result[-1][-1]) % (pow(10,9)+7)\n\n\n```
0
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put in `$1` more than the day before. On every subsequent Monday, he will put in `$1` more than the **previous Monday**. Given `n`, return _the total amount of money he will have in the Leetcode bank at the end of the_ `nth` _day._ **Example 1:** **Input:** n = 4 **Output:** 10 **Explanation:** After the 4th day, the total is 1 + 2 + 3 + 4 = 10. **Example 2:** **Input:** n = 10 **Output:** 37 **Explanation:** After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2. **Example 3:** **Input:** n = 20 **Output:** 96 **Explanation:** After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96. **Constraints:** * `1 <= n <= 1000`
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
[91.82% Faster] Easy DP solution, clean code and easy to understand
maximum-non-negative-product-in-a-matrix
0
1
<!-- # Intuition\nDescribe your first thoughts on how to solve this problem. -->\n![image.png](https://assets.leetcode.com/users/images/01acfa8c-1d89-4ba6-8e58-47d987295199_1679005995.2999926.png)\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nEach item in the DP matrix is a tuple that memorizes (max, min) result of the product.\n\n# Complexity\n- Time complexity: O(M*N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(M*N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxProductPath(self, grid: List[List[int]]) -> int:\n m,n = len(grid), len(grid[0])\n dp = [[[-inf, inf] for j in range(n)] for i in range(m)] \n - dp[0][0] = [grid[0][0],grid[0][0]]\n\n # Initialize row[0]\n for j in range(1, n):\n dp[0][j] = [dp[0][j-1][0] * grid[0][j], dp[0][j-1][1] * grid[0][j]]\n\n # Initialize column[0]\n for i in range(1, m):\n dp[i][0] = [dp[i-1][0][0] * grid[i][0], dp[i-1][0][0] * grid[i][0]]\n\n # DP matrix\n for i in range(1,m):\n for j in range(1,n): \n res = dp[i][j-1][0] * grid[i][j], \\\n dp[i][j-1][1] * grid[i][j], \\\n dp[i-1][j][0] * grid[i][j], \\\n dp[i-1][j][1] * grid[i][j]\n\n dp[i][j] = [max(res), min(res)]\n\n return -1 if dp[-1][-1][0] < 0 else dp[-1][-1][0] % (10**9 + 7)\n\n\n\n\n \n```
0
You are given a `m x n` matrix `grid`. Initially, you are located at the top-left corner `(0, 0)`, and in each step, you can only **move right or down** in the matrix. Among all possible paths starting from the top-left corner `(0, 0)` and ending in the bottom-right corner `(m - 1, n - 1)`, find the path with the **maximum non-negative product**. The product of a path is the product of all integers in the grid cells visited along the path. Return the _maximum non-negative product **modulo**_ `109 + 7`. _If the maximum product is **negative**, return_ `-1`. Notice that the modulo is performed after getting the maximum product. **Example 1:** **Input:** grid = \[\[-1,-2,-3\],\[-2,-3,-3\],\[-3,-3,-2\]\] **Output:** -1 **Explanation:** It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1. **Example 2:** **Input:** grid = \[\[1,-2,1\],\[1,-2,1\],\[3,-4,1\]\] **Output:** 8 **Explanation:** Maximum non-negative product is shown (1 \* 1 \* -2 \* -4 \* 1 = 8). **Example 3:** **Input:** grid = \[\[1,3\],\[0,-4\]\] **Output:** 0 **Explanation:** Maximum non-negative product is shown (1 \* 0 \* -4 = 0). **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 15` * `-4 <= grid[i][j] <= 4`
null
[91.82% Faster] Easy DP solution, clean code and easy to understand
maximum-non-negative-product-in-a-matrix
0
1
<!-- # Intuition\nDescribe your first thoughts on how to solve this problem. -->\n![image.png](https://assets.leetcode.com/users/images/01acfa8c-1d89-4ba6-8e58-47d987295199_1679005995.2999926.png)\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nEach item in the DP matrix is a tuple that memorizes (max, min) result of the product.\n\n# Complexity\n- Time complexity: O(M*N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(M*N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxProductPath(self, grid: List[List[int]]) -> int:\n m,n = len(grid), len(grid[0])\n dp = [[[-inf, inf] for j in range(n)] for i in range(m)] \n - dp[0][0] = [grid[0][0],grid[0][0]]\n\n # Initialize row[0]\n for j in range(1, n):\n dp[0][j] = [dp[0][j-1][0] * grid[0][j], dp[0][j-1][1] * grid[0][j]]\n\n # Initialize column[0]\n for i in range(1, m):\n dp[i][0] = [dp[i-1][0][0] * grid[i][0], dp[i-1][0][0] * grid[i][0]]\n\n # DP matrix\n for i in range(1,m):\n for j in range(1,n): \n res = dp[i][j-1][0] * grid[i][j], \\\n dp[i][j-1][1] * grid[i][j], \\\n dp[i-1][j][0] * grid[i][j], \\\n dp[i-1][j][1] * grid[i][j]\n\n dp[i][j] = [max(res), min(res)]\n\n return -1 if dp[-1][-1][0] < 0 else dp[-1][-1][0] % (10**9 + 7)\n\n\n\n\n \n```
0
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put in `$1` more than the day before. On every subsequent Monday, he will put in `$1` more than the **previous Monday**. Given `n`, return _the total amount of money he will have in the Leetcode bank at the end of the_ `nth` _day._ **Example 1:** **Input:** n = 4 **Output:** 10 **Explanation:** After the 4th day, the total is 1 + 2 + 3 + 4 = 10. **Example 2:** **Input:** n = 10 **Output:** 37 **Explanation:** After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2. **Example 3:** **Input:** n = 20 **Output:** 96 **Explanation:** After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96. **Constraints:** * `1 <= n <= 1000`
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
Python3 48ms solution.
maximum-non-negative-product-in-a-matrix
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy first thought to solve this problem is to use dynamic programming. By keeping track of the maximum and minimum product of subproblems, we can build up the answer for the entire grid.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nMy approach to solving this problem is to use a 2-dimensional dynamic programming approach. We can create two 2 dimensional arrays, one to store the maximum product and the other to store the minimum product of all subproblems. We can then fill up the arrays starting from the top left corner of the grid and work our way until we reach the bottom right corner. At each point, we can calculate the maximum and minimum product by multiplying the current element with the maximum and minimum product of the subproblems to the top and left of the current position. Finally, we can use the bottom right corner of the maximum product array to determine the result.\n\n# Complexity\n- Time complexity:$$O(n^2)$$ \n<!-- Add your time com plexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n^2)$$ \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxProductPath(self, grid: List[List[int]]) -> int:\n def helper(grid):\n n = len(grid)\n m = len(grid[0])\n dp = [[(0,0) for i in range(m)] for j in range(n)]\n dp[0][0] = (grid[0][0], grid[0][0])\n for i in range(1, m):\n dp[0][i] = (dp[0][i-1][0]*grid[0][i], dp[0][i-1][1]*grid[0][i])\n for i in range(1, n):\n dp[i][0] = (dp[i-1][0][0]*grid[i][0], dp[i-1][0][1]*grid[i][0])\n for i in range(1, n):\n for j in range(1, m):\n a = dp[i-1][j][0]*grid[i][j]\n b = dp[i-1][j][1]*grid[i][j]\n c = dp[i][j-1][0]*grid[i][j]\n d = dp[i][j-1][1]*grid[i][j]\n dp[i][j] = (max(a,b,c,d), min(a,b,c,d))\n return dp[n-1][m-1]\n ans = helper(grid)\n if ans[0] < 0:\n return -1\n return ans[0]%(10**9 + 7)\n```
0
You are given a `m x n` matrix `grid`. Initially, you are located at the top-left corner `(0, 0)`, and in each step, you can only **move right or down** in the matrix. Among all possible paths starting from the top-left corner `(0, 0)` and ending in the bottom-right corner `(m - 1, n - 1)`, find the path with the **maximum non-negative product**. The product of a path is the product of all integers in the grid cells visited along the path. Return the _maximum non-negative product **modulo**_ `109 + 7`. _If the maximum product is **negative**, return_ `-1`. Notice that the modulo is performed after getting the maximum product. **Example 1:** **Input:** grid = \[\[-1,-2,-3\],\[-2,-3,-3\],\[-3,-3,-2\]\] **Output:** -1 **Explanation:** It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1. **Example 2:** **Input:** grid = \[\[1,-2,1\],\[1,-2,1\],\[3,-4,1\]\] **Output:** 8 **Explanation:** Maximum non-negative product is shown (1 \* 1 \* -2 \* -4 \* 1 = 8). **Example 3:** **Input:** grid = \[\[1,3\],\[0,-4\]\] **Output:** 0 **Explanation:** Maximum non-negative product is shown (1 \* 0 \* -4 = 0). **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 15` * `-4 <= grid[i][j] <= 4`
null
Python3 48ms solution.
maximum-non-negative-product-in-a-matrix
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy first thought to solve this problem is to use dynamic programming. By keeping track of the maximum and minimum product of subproblems, we can build up the answer for the entire grid.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nMy approach to solving this problem is to use a 2-dimensional dynamic programming approach. We can create two 2 dimensional arrays, one to store the maximum product and the other to store the minimum product of all subproblems. We can then fill up the arrays starting from the top left corner of the grid and work our way until we reach the bottom right corner. At each point, we can calculate the maximum and minimum product by multiplying the current element with the maximum and minimum product of the subproblems to the top and left of the current position. Finally, we can use the bottom right corner of the maximum product array to determine the result.\n\n# Complexity\n- Time complexity:$$O(n^2)$$ \n<!-- Add your time com plexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n^2)$$ \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxProductPath(self, grid: List[List[int]]) -> int:\n def helper(grid):\n n = len(grid)\n m = len(grid[0])\n dp = [[(0,0) for i in range(m)] for j in range(n)]\n dp[0][0] = (grid[0][0], grid[0][0])\n for i in range(1, m):\n dp[0][i] = (dp[0][i-1][0]*grid[0][i], dp[0][i-1][1]*grid[0][i])\n for i in range(1, n):\n dp[i][0] = (dp[i-1][0][0]*grid[i][0], dp[i-1][0][1]*grid[i][0])\n for i in range(1, n):\n for j in range(1, m):\n a = dp[i-1][j][0]*grid[i][j]\n b = dp[i-1][j][1]*grid[i][j]\n c = dp[i][j-1][0]*grid[i][j]\n d = dp[i][j-1][1]*grid[i][j]\n dp[i][j] = (max(a,b,c,d), min(a,b,c,d))\n return dp[n-1][m-1]\n ans = helper(grid)\n if ans[0] < 0:\n return -1\n return ans[0]%(10**9 + 7)\n```
0
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put in `$1` more than the day before. On every subsequent Monday, he will put in `$1` more than the **previous Monday**. Given `n`, return _the total amount of money he will have in the Leetcode bank at the end of the_ `nth` _day._ **Example 1:** **Input:** n = 4 **Output:** 10 **Explanation:** After the 4th day, the total is 1 + 2 + 3 + 4 = 10. **Example 2:** **Input:** n = 10 **Output:** 37 **Explanation:** After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2. **Example 3:** **Input:** n = 20 **Output:** 96 **Explanation:** After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96. **Constraints:** * `1 <= n <= 1000`
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
LRU Cache for Speed, Memo if Memory | Pick Your Optimization
minimum-cost-to-connect-two-groups-of-points
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nA recursive solution can work well if you start to break down what the problem asks in concrete steps \n\nFor any graph of costs, there exists a min cost per column \nIf we know the min cost per column, then we can map out our cheapest connection via graph exploration \n\nThis is an iterative depth first based approach, and so needs memoization \n\nIf you have memory to spare, deepen as needed and use the lru cache. This will optimize time. If you don\'t have memory to spare, deepen while storing results in a memo. This will optimize space. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nGet dimension of graphical space in rows and cols. \nGet min value in column using zip and * to unpack cost into a min list\nMake a memo \n\nUse lru cache if speed is important \n\ndfs takes a row index and bitmask \n- if (rowindex, bitmask) in memo return that \n- elif row index is rows, calc as described in approach and memoize\n - return memoized value \n- else calc min of cost at row index, col index + dfs(row index + 1, bitmask | (1 << col_index)) for col index in range cols and memoize \n - return memoized value \n\nTo solve, do dfs based approach from root of 0, 0 \n\n\n# Complexity\n- Time complexity : O(N log N)\n - We end up exploring subtrees of size N log N due to memoization \n\n\n- Space complexity : O(N log N)\n - As above but for storage of results \n\nOne interesting takeaway is that various memo values at the end of one of the top runs could have union find done on them to speed up valuations later on. This may be of interest to some. \n\nDetailed walkthrough of example 3 in the code. \n\n# Code\n```\nclass Solution:\n def connectTwoGroups(self, cost: List[List[int]]) -> int:\n rows = len(cost)\n cols = len(cost[0])\n # set result as min cost in each cost set -> histogram intersection style \n min_value_in_column = [min(costs_i) for costs_i in zip(*cost)]\n self.memo = dict()\n\n @lru_cache(None)\n def dfs(row_index, bitmask) : \n if (row_index, bitmask) in self.memo :\n return self.memo[(row_index, bitmask)] \n elif row_index == rows : \n # return sum of min values in column for col index not in bitmask \n # bitmask & 1 << col_index == 0 -> least significant bit is 0 \n # this means that bitmask & (1 << col_i) match up -> this means we have this col index \n self.memo[(row_index, bitmask)] = sum(min_value_in_column[col_i] for col_i in range(cols) if not (bitmask & (1 << col_i)))\n return self.memo[(row_index, bitmask)]\n else : \n # otherwise, return minimum of cost at row index and col index + dfs(row_index + 1, mask union with (1 << col_index)) \n # which means, return cost found at row and col + dfs result of next row index if we join this col index to our bitmask (adds if not present) \n # which is done for col index in range cols \n # this means we take value at row and col and add to it the recursive value of the next row if we take the col index into the bitmask\n # this is done for each col index in range cols -> this finds the minimum then of this row item values plus next row items values recursively \n self.memo[(row_index, bitmask)] = min(cost[row_index][col_index] + dfs(row_index + 1, bitmask | (1 << col_index)) for col_index in range(cols))\n return self.memo[(row_index, bitmask)]\n # from the first row index with an empty mask \n # go until the last row index where \n # along the way to the last row index \n # for each row index consider each col index elements value with each next row index to rows \n # where upon reaching the last row in this manner you return the sum of the minimal items \n # for which you have selected such a mask as you go along \n \'\'\'\n Example 3 \n result -> [2, 1, 1]\n\n 2 5 1 0 row index, 0 bitmask goes in, must find following \n 3 4 7 find min of (2 + dfs(1, 1), 5 + dfs(1, 2), 1 + dfs(1, 4))\n 8 1 2 -> dfs(1, 1) -> find min (3 + dfs(2, 1), 4 + dfs(2, 3), 7 + dfs(2, 5))\n 6 2 4 dfs(2, 1) -> find min (8 + dfs(3, 1), 1 + dfs(3, 3), 2 + dfs(3, 5))\n 3 8 8 dfs(3, 1) -> find min (6 + dfs(4, 1), 2 + dfs(4, 3), 4 + dfs(4, 5))\n dfs(4, 1) -> find min (3 + 2, 8 + 2, 8 + 4)\n dfs(5, 1) -> for col 0, 1 has a value in col 0, so bitmask & (1 << col_i) is 1 -> so we skip this value. But other two we would get 0, so we add them for 2. \n dfs(5, 3) -> for col 1, b1 does not have value in col 1 which is like saying it does not have the second column -> add this value -> result is 2 \n dfs(5, 5) -> as above for col 2 -> total is now 2 for the first, and 2 for the other two, total is 4\n dfs(5, 7) -> 0 \n dfs(4, 1) -> so our first result is 3 + 2 is 5 \n dfs(4, 2) -> min(3 + 2, 8 + dfs(5, 2), 8 + dfs(5, 6)) -> 5 \n dfs(4, 3) -> min(3 + dfs(5, 3), 8 + dfs(5, 3), 8 + dfs(5, 7)) -> min (3 + 2, 8 + 2, 8 + 0) -> result is 5\n dfs(4, 4) -> min(3 + dfs(5, 5), 8 + dfs(5, 4), 8 + dfs(5, 6)) -> 7\n dfs(4, 6) -> min(3 + dfs(5, 7), 8 + dfs(5, 6), 8 + dfs(5, 6)) -> result is 3\n dfs(4, 5) -> min(3 + dfs(5, 5), 8 + dfs(5, 7), 8 + dfs(5, 5)) -> min (3 + 4, 8 + 0, 8 + 4) -> result is 7\n dfs(4, 7) -> min(3 + dfs(5, 7), 8 + dfs(5, 7), 8 + dfs(5, 7)) -> min (3, 8, 8) -> 3 \n dfs(3, 1) -> min (6 + 5, 2 + 5, 4 + 7) -> 7 \n dfs(3, 2) -> min (6 + 5, 2 + 5, 4+3) -> 7\n dfs(3, 3) -> min (6 + dfs(4, 3), 2 + dfs(4, 3), 4 + dfs(4, 7))\n -> min (6 + 5, 2 + 5, 4 + 3) -> 7\n dfs(3, 4) -> min (6 + 7, 2 + 7, 4+3) -> 7 \n dfs(3, 5) -> min(6 + dfs(4, 5), 2 + dfs(4, 7), 4 + dfs(4, 5))\n -> min(6 + 7, 2 + 3, 4 + 7) -> 5\n dfs(3, 6) -> min(6 + 3, 2 + 3, 4 + 3) -> 5\n dfs(3, 7) -> min(6 + dfs(4, 7), 2 + dfs(4, 7), 4+dfs(4, 7))\n -> min(6 + 3, 2 + 3, 4 + 3) -> 5 \n dfs(2, 1) -> (8 + 7, 1 + 7, 2 + 5) -> 7 \n dfs(2, 3) -> find min (8 + dfs(3, 3), 1 + dfs(3, 3), 2 + dfs(3, 7))\n -> min (8 + 7, 1 + 7, 2 + 5) -> 7\n dfs(2, 4) -> (8 + 5, 1 + 5, 2 + 7) -> 6\n dfs(2, 5) -> find min (8 + dfs(3, 5), 1 + dfs(3, 7), 2 + dfs(3, 5))\n -> min (8 + 5, 1 + 5, 2 + 5) -> 6\n dfs(2, 2) min (8 + dfs(3, 3), 1 + dfs(3, 2), 2 + dfs(3, 6))\n min (8 + 7, 1 + 7, 2 + 5) -> 7\n dfs(2, 6) -> min (8 + dfs(3, 7), 1 + dfs(3, 6), 2 + dfs(3, 6))\n min (8 + 5, 1 + 5, 2 + 5) -> 6\n dfs(2, 7) -> min (8 + dfs(3, 7), 1 + dfs(3, 7), 2 + dfs(3, 7)) -> 6\n dfs(1, 1) -> min(3 + 7, 4 + 7, 7 + 6) -> 10 \n dfs(0, 0) -> min(2 + 10, 5 + dfs(1, 2), 1 + dfs(1, 4))\n dfs(1, 2) -> min(3 + dfs(2, 3), 4 + dfs(2, 2), 7+ dfs(2, 6))\n -> min(3 + 7, 4 + 7, 7 + 6) -> 10\n dfs(0, 0) -> min(2 + 10, 5 + 10, 1 + dfs(1, 4)) \n dfs(1, 4) -> min(3 + 6, 4 + 6, 7 + 6) -> 9 \n dfs(0, 0) -> min(2 + 10, 5 + 10, 1 + 9) -> 10\n \'\'\' \n\n return dfs(0, 0)\n```
0
You are given two groups of points where the first group has `size1` points, the second group has `size2` points, and `size1 >= size2`. The `cost` of the connection between any two points are given in an `size1 x size2` matrix where `cost[i][j]` is the cost of connecting point `i` of the first group and point `j` of the second group. The groups are connected if **each point in both groups is connected to one or more points in the opposite group**. In other words, each point in the first group must be connected to at least one point in the second group, and each point in the second group must be connected to at least one point in the first group. Return _the minimum cost it takes to connect the two groups_. **Example 1:** **Input:** cost = \[\[15, 96\], \[36, 2\]\] **Output:** 17 **Explanation**: The optimal way of connecting the groups is: 1--A 2--B This results in a total cost of 17. **Example 2:** **Input:** cost = \[\[1, 3, 5\], \[4, 1, 1\], \[1, 5, 3\]\] **Output:** 4 **Explanation**: The optimal way of connecting the groups is: 1--A 2--B 2--C 3--A This results in a total cost of 4. Note that there are multiple points connected to point 2 in the first group and point A in the second group. This does not matter as there is no limit to the number of points that can be connected. We only care about the minimum total cost. **Example 3:** **Input:** cost = \[\[2, 5, 1\], \[3, 4, 7\], \[8, 1, 2\], \[6, 2, 4\], \[3, 8, 8\]\] **Output:** 10 **Constraints:** * `size1 == cost.length` * `size2 == cost[i].length` * `1 <= size1, size2 <= 12` * `size1 >= size2` * `0 <= cost[i][j] <= 100`
null
LRU Cache for Speed, Memo if Memory | Pick Your Optimization
minimum-cost-to-connect-two-groups-of-points
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nA recursive solution can work well if you start to break down what the problem asks in concrete steps \n\nFor any graph of costs, there exists a min cost per column \nIf we know the min cost per column, then we can map out our cheapest connection via graph exploration \n\nThis is an iterative depth first based approach, and so needs memoization \n\nIf you have memory to spare, deepen as needed and use the lru cache. This will optimize time. If you don\'t have memory to spare, deepen while storing results in a memo. This will optimize space. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nGet dimension of graphical space in rows and cols. \nGet min value in column using zip and * to unpack cost into a min list\nMake a memo \n\nUse lru cache if speed is important \n\ndfs takes a row index and bitmask \n- if (rowindex, bitmask) in memo return that \n- elif row index is rows, calc as described in approach and memoize\n - return memoized value \n- else calc min of cost at row index, col index + dfs(row index + 1, bitmask | (1 << col_index)) for col index in range cols and memoize \n - return memoized value \n\nTo solve, do dfs based approach from root of 0, 0 \n\n\n# Complexity\n- Time complexity : O(N log N)\n - We end up exploring subtrees of size N log N due to memoization \n\n\n- Space complexity : O(N log N)\n - As above but for storage of results \n\nOne interesting takeaway is that various memo values at the end of one of the top runs could have union find done on them to speed up valuations later on. This may be of interest to some. \n\nDetailed walkthrough of example 3 in the code. \n\n# Code\n```\nclass Solution:\n def connectTwoGroups(self, cost: List[List[int]]) -> int:\n rows = len(cost)\n cols = len(cost[0])\n # set result as min cost in each cost set -> histogram intersection style \n min_value_in_column = [min(costs_i) for costs_i in zip(*cost)]\n self.memo = dict()\n\n @lru_cache(None)\n def dfs(row_index, bitmask) : \n if (row_index, bitmask) in self.memo :\n return self.memo[(row_index, bitmask)] \n elif row_index == rows : \n # return sum of min values in column for col index not in bitmask \n # bitmask & 1 << col_index == 0 -> least significant bit is 0 \n # this means that bitmask & (1 << col_i) match up -> this means we have this col index \n self.memo[(row_index, bitmask)] = sum(min_value_in_column[col_i] for col_i in range(cols) if not (bitmask & (1 << col_i)))\n return self.memo[(row_index, bitmask)]\n else : \n # otherwise, return minimum of cost at row index and col index + dfs(row_index + 1, mask union with (1 << col_index)) \n # which means, return cost found at row and col + dfs result of next row index if we join this col index to our bitmask (adds if not present) \n # which is done for col index in range cols \n # this means we take value at row and col and add to it the recursive value of the next row if we take the col index into the bitmask\n # this is done for each col index in range cols -> this finds the minimum then of this row item values plus next row items values recursively \n self.memo[(row_index, bitmask)] = min(cost[row_index][col_index] + dfs(row_index + 1, bitmask | (1 << col_index)) for col_index in range(cols))\n return self.memo[(row_index, bitmask)]\n # from the first row index with an empty mask \n # go until the last row index where \n # along the way to the last row index \n # for each row index consider each col index elements value with each next row index to rows \n # where upon reaching the last row in this manner you return the sum of the minimal items \n # for which you have selected such a mask as you go along \n \'\'\'\n Example 3 \n result -> [2, 1, 1]\n\n 2 5 1 0 row index, 0 bitmask goes in, must find following \n 3 4 7 find min of (2 + dfs(1, 1), 5 + dfs(1, 2), 1 + dfs(1, 4))\n 8 1 2 -> dfs(1, 1) -> find min (3 + dfs(2, 1), 4 + dfs(2, 3), 7 + dfs(2, 5))\n 6 2 4 dfs(2, 1) -> find min (8 + dfs(3, 1), 1 + dfs(3, 3), 2 + dfs(3, 5))\n 3 8 8 dfs(3, 1) -> find min (6 + dfs(4, 1), 2 + dfs(4, 3), 4 + dfs(4, 5))\n dfs(4, 1) -> find min (3 + 2, 8 + 2, 8 + 4)\n dfs(5, 1) -> for col 0, 1 has a value in col 0, so bitmask & (1 << col_i) is 1 -> so we skip this value. But other two we would get 0, so we add them for 2. \n dfs(5, 3) -> for col 1, b1 does not have value in col 1 which is like saying it does not have the second column -> add this value -> result is 2 \n dfs(5, 5) -> as above for col 2 -> total is now 2 for the first, and 2 for the other two, total is 4\n dfs(5, 7) -> 0 \n dfs(4, 1) -> so our first result is 3 + 2 is 5 \n dfs(4, 2) -> min(3 + 2, 8 + dfs(5, 2), 8 + dfs(5, 6)) -> 5 \n dfs(4, 3) -> min(3 + dfs(5, 3), 8 + dfs(5, 3), 8 + dfs(5, 7)) -> min (3 + 2, 8 + 2, 8 + 0) -> result is 5\n dfs(4, 4) -> min(3 + dfs(5, 5), 8 + dfs(5, 4), 8 + dfs(5, 6)) -> 7\n dfs(4, 6) -> min(3 + dfs(5, 7), 8 + dfs(5, 6), 8 + dfs(5, 6)) -> result is 3\n dfs(4, 5) -> min(3 + dfs(5, 5), 8 + dfs(5, 7), 8 + dfs(5, 5)) -> min (3 + 4, 8 + 0, 8 + 4) -> result is 7\n dfs(4, 7) -> min(3 + dfs(5, 7), 8 + dfs(5, 7), 8 + dfs(5, 7)) -> min (3, 8, 8) -> 3 \n dfs(3, 1) -> min (6 + 5, 2 + 5, 4 + 7) -> 7 \n dfs(3, 2) -> min (6 + 5, 2 + 5, 4+3) -> 7\n dfs(3, 3) -> min (6 + dfs(4, 3), 2 + dfs(4, 3), 4 + dfs(4, 7))\n -> min (6 + 5, 2 + 5, 4 + 3) -> 7\n dfs(3, 4) -> min (6 + 7, 2 + 7, 4+3) -> 7 \n dfs(3, 5) -> min(6 + dfs(4, 5), 2 + dfs(4, 7), 4 + dfs(4, 5))\n -> min(6 + 7, 2 + 3, 4 + 7) -> 5\n dfs(3, 6) -> min(6 + 3, 2 + 3, 4 + 3) -> 5\n dfs(3, 7) -> min(6 + dfs(4, 7), 2 + dfs(4, 7), 4+dfs(4, 7))\n -> min(6 + 3, 2 + 3, 4 + 3) -> 5 \n dfs(2, 1) -> (8 + 7, 1 + 7, 2 + 5) -> 7 \n dfs(2, 3) -> find min (8 + dfs(3, 3), 1 + dfs(3, 3), 2 + dfs(3, 7))\n -> min (8 + 7, 1 + 7, 2 + 5) -> 7\n dfs(2, 4) -> (8 + 5, 1 + 5, 2 + 7) -> 6\n dfs(2, 5) -> find min (8 + dfs(3, 5), 1 + dfs(3, 7), 2 + dfs(3, 5))\n -> min (8 + 5, 1 + 5, 2 + 5) -> 6\n dfs(2, 2) min (8 + dfs(3, 3), 1 + dfs(3, 2), 2 + dfs(3, 6))\n min (8 + 7, 1 + 7, 2 + 5) -> 7\n dfs(2, 6) -> min (8 + dfs(3, 7), 1 + dfs(3, 6), 2 + dfs(3, 6))\n min (8 + 5, 1 + 5, 2 + 5) -> 6\n dfs(2, 7) -> min (8 + dfs(3, 7), 1 + dfs(3, 7), 2 + dfs(3, 7)) -> 6\n dfs(1, 1) -> min(3 + 7, 4 + 7, 7 + 6) -> 10 \n dfs(0, 0) -> min(2 + 10, 5 + dfs(1, 2), 1 + dfs(1, 4))\n dfs(1, 2) -> min(3 + dfs(2, 3), 4 + dfs(2, 2), 7+ dfs(2, 6))\n -> min(3 + 7, 4 + 7, 7 + 6) -> 10\n dfs(0, 0) -> min(2 + 10, 5 + 10, 1 + dfs(1, 4)) \n dfs(1, 4) -> min(3 + 6, 4 + 6, 7 + 6) -> 9 \n dfs(0, 0) -> min(2 + 10, 5 + 10, 1 + 9) -> 10\n \'\'\' \n\n return dfs(0, 0)\n```
0
You are given a string `s` and two integers `x` and `y`. You can perform two types of operations any number of times. * Remove substring `"ab "` and gain `x` points. * For example, when removing `"ab "` from `"cabxbae "` it becomes `"cxbae "`. * Remove substring `"ba "` and gain `y` points. * For example, when removing `"ba "` from `"cabxbae "` it becomes `"cabxe "`. Return _the maximum points you can gain after applying the above operations on_ `s`. **Example 1:** **Input:** s = "cdbcbbaaabab ", x = 4, y = 5 **Output:** 19 **Explanation:** - Remove the "ba " underlined in "cdbcbbaaabab ". Now, s = "cdbcbbaaab " and 5 points are added to the score. - Remove the "ab " underlined in "cdbcbbaaab ". Now, s = "cdbcbbaa " and 4 points are added to the score. - Remove the "ba " underlined in "cdbcbbaa ". Now, s = "cdbcba " and 5 points are added to the score. - Remove the "ba " underlined in "cdbcba ". Now, s = "cdbc " and 5 points are added to the score. Total score = 5 + 4 + 5 + 5 = 19. **Example 2:** **Input:** s = "aabbaaxybbaabb ", x = 5, y = 4 **Output:** 20 **Constraints:** * `1 <= s.length <= 105` * `1 <= x, y <= 104` * `s` consists of lowercase English letters.
Each point on the left would either be connected to exactly point already connected to some left node, or a subset of the nodes on the right which are not connected to any node Use dynamic programming with bitmasking, where the state will be (number of points assigned in first group, bitmask of points assigned in second group).
Python (Simple DP + Bitmasking)
minimum-cost-to-connect-two-groups-of-points
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def connectTwoGroups(self, cost):\n m, n = len(cost), len(cost[0])\n\n ans = [min(i) for i in zip(*cost)]\n\n @lru_cache(None)\n def dfs(i,mask):\n if i == m: return sum(ans[j] for j in range(n) if not (mask & (1<<j)))\n return min(cost[i][j] + dfs(i+1,mask|(1<<j)) for j in range(n))\n\n return dfs(0,0)\n\n\n\n\n\n \n\n```
1
You are given two groups of points where the first group has `size1` points, the second group has `size2` points, and `size1 >= size2`. The `cost` of the connection between any two points are given in an `size1 x size2` matrix where `cost[i][j]` is the cost of connecting point `i` of the first group and point `j` of the second group. The groups are connected if **each point in both groups is connected to one or more points in the opposite group**. In other words, each point in the first group must be connected to at least one point in the second group, and each point in the second group must be connected to at least one point in the first group. Return _the minimum cost it takes to connect the two groups_. **Example 1:** **Input:** cost = \[\[15, 96\], \[36, 2\]\] **Output:** 17 **Explanation**: The optimal way of connecting the groups is: 1--A 2--B This results in a total cost of 17. **Example 2:** **Input:** cost = \[\[1, 3, 5\], \[4, 1, 1\], \[1, 5, 3\]\] **Output:** 4 **Explanation**: The optimal way of connecting the groups is: 1--A 2--B 2--C 3--A This results in a total cost of 4. Note that there are multiple points connected to point 2 in the first group and point A in the second group. This does not matter as there is no limit to the number of points that can be connected. We only care about the minimum total cost. **Example 3:** **Input:** cost = \[\[2, 5, 1\], \[3, 4, 7\], \[8, 1, 2\], \[6, 2, 4\], \[3, 8, 8\]\] **Output:** 10 **Constraints:** * `size1 == cost.length` * `size2 == cost[i].length` * `1 <= size1, size2 <= 12` * `size1 >= size2` * `0 <= cost[i][j] <= 100`
null
Python (Simple DP + Bitmasking)
minimum-cost-to-connect-two-groups-of-points
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def connectTwoGroups(self, cost):\n m, n = len(cost), len(cost[0])\n\n ans = [min(i) for i in zip(*cost)]\n\n @lru_cache(None)\n def dfs(i,mask):\n if i == m: return sum(ans[j] for j in range(n) if not (mask & (1<<j)))\n return min(cost[i][j] + dfs(i+1,mask|(1<<j)) for j in range(n))\n\n return dfs(0,0)\n\n\n\n\n\n \n\n```
1
You are given a string `s` and two integers `x` and `y`. You can perform two types of operations any number of times. * Remove substring `"ab "` and gain `x` points. * For example, when removing `"ab "` from `"cabxbae "` it becomes `"cxbae "`. * Remove substring `"ba "` and gain `y` points. * For example, when removing `"ba "` from `"cabxbae "` it becomes `"cabxe "`. Return _the maximum points you can gain after applying the above operations on_ `s`. **Example 1:** **Input:** s = "cdbcbbaaabab ", x = 4, y = 5 **Output:** 19 **Explanation:** - Remove the "ba " underlined in "cdbcbbaaabab ". Now, s = "cdbcbbaaab " and 5 points are added to the score. - Remove the "ab " underlined in "cdbcbbaaab ". Now, s = "cdbcbbaa " and 4 points are added to the score. - Remove the "ba " underlined in "cdbcbbaa ". Now, s = "cdbcba " and 5 points are added to the score. - Remove the "ba " underlined in "cdbcba ". Now, s = "cdbc " and 5 points are added to the score. Total score = 5 + 4 + 5 + 5 = 19. **Example 2:** **Input:** s = "aabbaaxybbaabb ", x = 5, y = 4 **Output:** 20 **Constraints:** * `1 <= s.length <= 105` * `1 <= x, y <= 104` * `s` consists of lowercase English letters.
Each point on the left would either be connected to exactly point already connected to some left node, or a subset of the nodes on the right which are not connected to any node Use dynamic programming with bitmasking, where the state will be (number of points assigned in first group, bitmask of points assigned in second group).
[Python3] top-down dp
minimum-cost-to-connect-two-groups-of-points
0
1
\n```\nclass Solution:\n def connectTwoGroups(self, cost: List[List[int]]) -> int:\n m, n = len(cost), len(cost[0])\n mn = [min(x) for x in zip(*cost)] # min cost of connecting points in 2nd group \n \n @lru_cache(None)\n def fn(i, mask):\n """Return min cost of connecting group1[i:] and group2 represented as mask."""\n if i == m: return sum(mn[j] for j in range(n) if not (mask & (1<<j)))\n return min(cost[i][j] + fn(i+1, mask | 1<<j) for j in range(n))\n \n return fn(0, 0)\n```\n\nor symmetrically \n```\nclass Solution:\n def connectTwoGroups(self, cost: List[List[int]]) -> int:\n m, n = len(cost), len(cost[0])\n mn = [min(x) for x in cost] # min cost of connecting points in 1st group \n \n @lru_cache(None)\n def fn(j, mask):\n """Return min cost of connecting group1[i:] and group2 represented as mask."""\n if j == n: return sum(mn[i] for i in range(m) if not (mask & (1<<i)))\n return min(cost[i][j] + fn(j+1, mask | 1<<i) for i in range(m))\n \n return fn(0, 0)\n```
2
You are given two groups of points where the first group has `size1` points, the second group has `size2` points, and `size1 >= size2`. The `cost` of the connection between any two points are given in an `size1 x size2` matrix where `cost[i][j]` is the cost of connecting point `i` of the first group and point `j` of the second group. The groups are connected if **each point in both groups is connected to one or more points in the opposite group**. In other words, each point in the first group must be connected to at least one point in the second group, and each point in the second group must be connected to at least one point in the first group. Return _the minimum cost it takes to connect the two groups_. **Example 1:** **Input:** cost = \[\[15, 96\], \[36, 2\]\] **Output:** 17 **Explanation**: The optimal way of connecting the groups is: 1--A 2--B This results in a total cost of 17. **Example 2:** **Input:** cost = \[\[1, 3, 5\], \[4, 1, 1\], \[1, 5, 3\]\] **Output:** 4 **Explanation**: The optimal way of connecting the groups is: 1--A 2--B 2--C 3--A This results in a total cost of 4. Note that there are multiple points connected to point 2 in the first group and point A in the second group. This does not matter as there is no limit to the number of points that can be connected. We only care about the minimum total cost. **Example 3:** **Input:** cost = \[\[2, 5, 1\], \[3, 4, 7\], \[8, 1, 2\], \[6, 2, 4\], \[3, 8, 8\]\] **Output:** 10 **Constraints:** * `size1 == cost.length` * `size2 == cost[i].length` * `1 <= size1, size2 <= 12` * `size1 >= size2` * `0 <= cost[i][j] <= 100`
null
[Python3] top-down dp
minimum-cost-to-connect-two-groups-of-points
0
1
\n```\nclass Solution:\n def connectTwoGroups(self, cost: List[List[int]]) -> int:\n m, n = len(cost), len(cost[0])\n mn = [min(x) for x in zip(*cost)] # min cost of connecting points in 2nd group \n \n @lru_cache(None)\n def fn(i, mask):\n """Return min cost of connecting group1[i:] and group2 represented as mask."""\n if i == m: return sum(mn[j] for j in range(n) if not (mask & (1<<j)))\n return min(cost[i][j] + fn(i+1, mask | 1<<j) for j in range(n))\n \n return fn(0, 0)\n```\n\nor symmetrically \n```\nclass Solution:\n def connectTwoGroups(self, cost: List[List[int]]) -> int:\n m, n = len(cost), len(cost[0])\n mn = [min(x) for x in cost] # min cost of connecting points in 1st group \n \n @lru_cache(None)\n def fn(j, mask):\n """Return min cost of connecting group1[i:] and group2 represented as mask."""\n if j == n: return sum(mn[i] for i in range(m) if not (mask & (1<<i)))\n return min(cost[i][j] + fn(j+1, mask | 1<<i) for i in range(m))\n \n return fn(0, 0)\n```
2
You are given a string `s` and two integers `x` and `y`. You can perform two types of operations any number of times. * Remove substring `"ab "` and gain `x` points. * For example, when removing `"ab "` from `"cabxbae "` it becomes `"cxbae "`. * Remove substring `"ba "` and gain `y` points. * For example, when removing `"ba "` from `"cabxbae "` it becomes `"cabxe "`. Return _the maximum points you can gain after applying the above operations on_ `s`. **Example 1:** **Input:** s = "cdbcbbaaabab ", x = 4, y = 5 **Output:** 19 **Explanation:** - Remove the "ba " underlined in "cdbcbbaaabab ". Now, s = "cdbcbbaaab " and 5 points are added to the score. - Remove the "ab " underlined in "cdbcbbaaab ". Now, s = "cdbcbbaa " and 4 points are added to the score. - Remove the "ba " underlined in "cdbcbbaa ". Now, s = "cdbcba " and 5 points are added to the score. - Remove the "ba " underlined in "cdbcba ". Now, s = "cdbc " and 5 points are added to the score. Total score = 5 + 4 + 5 + 5 = 19. **Example 2:** **Input:** s = "aabbaaxybbaabb ", x = 5, y = 4 **Output:** 20 **Constraints:** * `1 <= s.length <= 105` * `1 <= x, y <= 104` * `s` consists of lowercase English letters.
Each point on the left would either be connected to exactly point already connected to some left node, or a subset of the nodes on the right which are not connected to any node Use dynamic programming with bitmasking, where the state will be (number of points assigned in first group, bitmask of points assigned in second group).
[Python] BFS with heapq and bit tricks. 90ms, beats 100%
minimum-cost-to-connect-two-groups-of-points
0
1
The special size handling at the top makes things a bit faster; taking all the zero-cost edges before BFS gives about 50% speed boost as well, although the code still beats 100% without those.\n\nThere are 3 optimizations over other BFS or DFS solutions that are big:\n1. ```if first_mask != mask_i: ``` splits the case where the first group is matched, so we can greedily take the minimum cost edge for each second group vertex and add a \'fully matched\' entry to the queue.\n2. ```i = ((first_mask + 1) & (-first_mask - 1)) ``` looks crazy if you\'ve never seen it. This sets i to the least significant zero bit of first_mask. I highly suggest checking out Fenwick trees, since their implementation uses this trick. This works because: (x & -x) gives you the least significant bit of x, AND the LSB of x+1 is the first zero bit of x.\n3. There are two types of edges we consider adding if we\'ve chosen a vertex i in the first group: Edges (i, j) where j is also unmatched, or edges (i, j) where cost[i][j] is the smallest cost in row cost[i]\n\nFull code:\n\n```python\ndef connectTwoGroups(self, cost: List[List[int]]) -> int:\n\tsize_i, size_j = len(cost), len(cost[0])\n\n\t# Optimizations if we have <=2 columns\n\tif size_j == 1:\n\t\treturn sum(row[0] for row in cost)\n\tif size_j == 2:\n\t\ttot = min(cost[0])\n\t\tused = (1 if tot==cost[0][0] else 2) # bitmask for which column we\'ve used\n\t\tmin_extra = max(cost[0]) - tot # extra cost to use the max value in this row\n\n\t\tfor j in range(1, size_i):\n\t\t\tmin_in_row = min(cost[j])\n\t\t\ttot += min_in_row\n\t\t\tmin_extra = min(min_in_row, max(cost[j])-min_in_row)\n\t\t\tused |= (1 if min_in_row == cost[j][0] else 2)\n\n\t\tif used == 3: # used both cols already\n\t\t\treturn tot\n\t\telse: # One row needs to use a non-min element\n\t\t\treturn tot+min_extra\n\n\tmask_i = (1 << size_i) - 1\n\tmask_j = (1 << size_j) - 1\n\tfully_connected = (mask_i, mask_j)\n\n\tstart_row, start_col = 0, 0\n\tmin_by_col = [min([cost[i][col] for i in range(size_i)]) for col in range(size_j)] # Min value by column\n\n\t# Always take any cost 0 edges\n\tfor j in range(size_j):\n\t\tif min_by_col[j] == 0:\n\t\t\tstart_col += (1 << j)\n\tmin_by_row = [min(row) for row in cost]\n\tfor i in range(size_i):\n\t\tif min_by_row[i] == 0:\n\t\t\tstart_row += (1 << i)\n\n\tvisited = set()\n\tQ = [(0, start_row, start_col)]\n\n\theapqpop = heapq.heappop\n\theapqpush = heapq.heappush\n\twhile True:\n\t\ttotal_cost, first_mask, second_mask = heapqpop(Q)\n\n\t\tif (first_mask, second_mask) == fully_connected:\n\t\t\treturn total_cost\n\n\t\tif (first_mask, second_mask) in visited:\n\t\t\tcontinue\n\n\t\tvisited.add((first_mask, second_mask))\n\n\t\tif first_mask != mask_i:\n\t\t\ti = ((first_mask + 1) & (-first_mask - 1)) # Get the smallest unset bit of first_mask\n\t\t\tfirst_mask += i\n\t\t\ti = i.bit_length() - 1 # Convert bit to index\n\t\t\tshifted = 1\n\t\t\tfor j in range(size_j):\n\t\t\t\tif (second_mask & shifted) == 0: # If jth col is currently edgeless\n\t\t\t\t\theapqpush(Q, (total_cost + cost[i][j], first_mask, second_mask + shifted))\n\t\t\t\telif cost[i][j] == min_by_row[i]: # Or else (i,j) is i\'s minimum weight edge\n\t\t\t\t\theapqpush(Q, (total_cost + min_by_row[i], first_mask, second_mask))\n\t\t\t\tshifted += shifted\n\n\t\telse: # group 1 all matched, find cost to fill rest of the graph\n\t\t\tshifted = 1\n\t\t\tfor j in range(size_j):\n\t\t\t\tif (second_mask & shifted) == 0:\n\t\t\t\t\ttotal_cost += min_by_col[j]\n\t\t\t\tshifted += shifted\n\t\t\theapqpush(Q, (total_cost, mask_i, mask_j))\n```
1
You are given two groups of points where the first group has `size1` points, the second group has `size2` points, and `size1 >= size2`. The `cost` of the connection between any two points are given in an `size1 x size2` matrix where `cost[i][j]` is the cost of connecting point `i` of the first group and point `j` of the second group. The groups are connected if **each point in both groups is connected to one or more points in the opposite group**. In other words, each point in the first group must be connected to at least one point in the second group, and each point in the second group must be connected to at least one point in the first group. Return _the minimum cost it takes to connect the two groups_. **Example 1:** **Input:** cost = \[\[15, 96\], \[36, 2\]\] **Output:** 17 **Explanation**: The optimal way of connecting the groups is: 1--A 2--B This results in a total cost of 17. **Example 2:** **Input:** cost = \[\[1, 3, 5\], \[4, 1, 1\], \[1, 5, 3\]\] **Output:** 4 **Explanation**: The optimal way of connecting the groups is: 1--A 2--B 2--C 3--A This results in a total cost of 4. Note that there are multiple points connected to point 2 in the first group and point A in the second group. This does not matter as there is no limit to the number of points that can be connected. We only care about the minimum total cost. **Example 3:** **Input:** cost = \[\[2, 5, 1\], \[3, 4, 7\], \[8, 1, 2\], \[6, 2, 4\], \[3, 8, 8\]\] **Output:** 10 **Constraints:** * `size1 == cost.length` * `size2 == cost[i].length` * `1 <= size1, size2 <= 12` * `size1 >= size2` * `0 <= cost[i][j] <= 100`
null
[Python] BFS with heapq and bit tricks. 90ms, beats 100%
minimum-cost-to-connect-two-groups-of-points
0
1
The special size handling at the top makes things a bit faster; taking all the zero-cost edges before BFS gives about 50% speed boost as well, although the code still beats 100% without those.\n\nThere are 3 optimizations over other BFS or DFS solutions that are big:\n1. ```if first_mask != mask_i: ``` splits the case where the first group is matched, so we can greedily take the minimum cost edge for each second group vertex and add a \'fully matched\' entry to the queue.\n2. ```i = ((first_mask + 1) & (-first_mask - 1)) ``` looks crazy if you\'ve never seen it. This sets i to the least significant zero bit of first_mask. I highly suggest checking out Fenwick trees, since their implementation uses this trick. This works because: (x & -x) gives you the least significant bit of x, AND the LSB of x+1 is the first zero bit of x.\n3. There are two types of edges we consider adding if we\'ve chosen a vertex i in the first group: Edges (i, j) where j is also unmatched, or edges (i, j) where cost[i][j] is the smallest cost in row cost[i]\n\nFull code:\n\n```python\ndef connectTwoGroups(self, cost: List[List[int]]) -> int:\n\tsize_i, size_j = len(cost), len(cost[0])\n\n\t# Optimizations if we have <=2 columns\n\tif size_j == 1:\n\t\treturn sum(row[0] for row in cost)\n\tif size_j == 2:\n\t\ttot = min(cost[0])\n\t\tused = (1 if tot==cost[0][0] else 2) # bitmask for which column we\'ve used\n\t\tmin_extra = max(cost[0]) - tot # extra cost to use the max value in this row\n\n\t\tfor j in range(1, size_i):\n\t\t\tmin_in_row = min(cost[j])\n\t\t\ttot += min_in_row\n\t\t\tmin_extra = min(min_in_row, max(cost[j])-min_in_row)\n\t\t\tused |= (1 if min_in_row == cost[j][0] else 2)\n\n\t\tif used == 3: # used both cols already\n\t\t\treturn tot\n\t\telse: # One row needs to use a non-min element\n\t\t\treturn tot+min_extra\n\n\tmask_i = (1 << size_i) - 1\n\tmask_j = (1 << size_j) - 1\n\tfully_connected = (mask_i, mask_j)\n\n\tstart_row, start_col = 0, 0\n\tmin_by_col = [min([cost[i][col] for i in range(size_i)]) for col in range(size_j)] # Min value by column\n\n\t# Always take any cost 0 edges\n\tfor j in range(size_j):\n\t\tif min_by_col[j] == 0:\n\t\t\tstart_col += (1 << j)\n\tmin_by_row = [min(row) for row in cost]\n\tfor i in range(size_i):\n\t\tif min_by_row[i] == 0:\n\t\t\tstart_row += (1 << i)\n\n\tvisited = set()\n\tQ = [(0, start_row, start_col)]\n\n\theapqpop = heapq.heappop\n\theapqpush = heapq.heappush\n\twhile True:\n\t\ttotal_cost, first_mask, second_mask = heapqpop(Q)\n\n\t\tif (first_mask, second_mask) == fully_connected:\n\t\t\treturn total_cost\n\n\t\tif (first_mask, second_mask) in visited:\n\t\t\tcontinue\n\n\t\tvisited.add((first_mask, second_mask))\n\n\t\tif first_mask != mask_i:\n\t\t\ti = ((first_mask + 1) & (-first_mask - 1)) # Get the smallest unset bit of first_mask\n\t\t\tfirst_mask += i\n\t\t\ti = i.bit_length() - 1 # Convert bit to index\n\t\t\tshifted = 1\n\t\t\tfor j in range(size_j):\n\t\t\t\tif (second_mask & shifted) == 0: # If jth col is currently edgeless\n\t\t\t\t\theapqpush(Q, (total_cost + cost[i][j], first_mask, second_mask + shifted))\n\t\t\t\telif cost[i][j] == min_by_row[i]: # Or else (i,j) is i\'s minimum weight edge\n\t\t\t\t\theapqpush(Q, (total_cost + min_by_row[i], first_mask, second_mask))\n\t\t\t\tshifted += shifted\n\n\t\telse: # group 1 all matched, find cost to fill rest of the graph\n\t\t\tshifted = 1\n\t\t\tfor j in range(size_j):\n\t\t\t\tif (second_mask & shifted) == 0:\n\t\t\t\t\ttotal_cost += min_by_col[j]\n\t\t\t\tshifted += shifted\n\t\t\theapqpush(Q, (total_cost, mask_i, mask_j))\n```
1
You are given a string `s` and two integers `x` and `y`. You can perform two types of operations any number of times. * Remove substring `"ab "` and gain `x` points. * For example, when removing `"ab "` from `"cabxbae "` it becomes `"cxbae "`. * Remove substring `"ba "` and gain `y` points. * For example, when removing `"ba "` from `"cabxbae "` it becomes `"cabxe "`. Return _the maximum points you can gain after applying the above operations on_ `s`. **Example 1:** **Input:** s = "cdbcbbaaabab ", x = 4, y = 5 **Output:** 19 **Explanation:** - Remove the "ba " underlined in "cdbcbbaaabab ". Now, s = "cdbcbbaaab " and 5 points are added to the score. - Remove the "ab " underlined in "cdbcbbaaab ". Now, s = "cdbcbbaa " and 4 points are added to the score. - Remove the "ba " underlined in "cdbcbbaa ". Now, s = "cdbcba " and 5 points are added to the score. - Remove the "ba " underlined in "cdbcba ". Now, s = "cdbc " and 5 points are added to the score. Total score = 5 + 4 + 5 + 5 = 19. **Example 2:** **Input:** s = "aabbaaxybbaabb ", x = 5, y = 4 **Output:** 20 **Constraints:** * `1 <= s.length <= 105` * `1 <= x, y <= 104` * `s` consists of lowercase English letters.
Each point on the left would either be connected to exactly point already connected to some left node, or a subset of the nodes on the right which are not connected to any node Use dynamic programming with bitmasking, where the state will be (number of points assigned in first group, bitmask of points assigned in second group).
Very simple, self-explanatory stack based solution
crawler-log-folder
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n# Code\n```\nclass Solution:\n def minOperations(self, logs: List[str]) -> int:\n stack = [] \n for lg in logs:\n if lg != \'./\':\n if lg != \'../\':\n stack.append(lg)\n else:\n if stack:\n stack.pop()\n return len(stack)\n\n\n\n\n```
1
The Leetcode file system keeps a log each time some user performs a _change folder_ operation. The operations are described below: * `"../ "` : Move to the parent folder of the current folder. (If you are already in the main folder, **remain in the same folder**). * `"./ "` : Remain in the same folder. * `"x/ "` : Move to the child folder named `x` (This folder is **guaranteed to always exist**). You are given a list of strings `logs` where `logs[i]` is the operation performed by the user at the `ith` step. The file system starts in the main folder, then the operations in `logs` are performed. Return _the minimum number of operations needed to go back to the main folder after the change folder operations._ **Example 1:** **Input:** logs = \[ "d1/ ", "d2/ ", "../ ", "d21/ ", "./ "\] **Output:** 2 **Explanation:** Use this change folder operation "../ " 2 times and go back to the main folder. **Example 2:** **Input:** logs = \[ "d1/ ", "d2/ ", "./ ", "d3/ ", "../ ", "d31/ "\] **Output:** 3 **Example 3:** **Input:** logs = \[ "d1/ ", "../ ", "../ ", "../ "\] **Output:** 0 **Constraints:** * `1 <= logs.length <= 103` * `2 <= logs[i].length <= 10` * `logs[i]` contains lowercase English letters, digits, `'.'`, and `'/'`. * `logs[i]` follows the format described in the statement. * Folder names consist of lowercase English letters and digits.
null
Very simple, self-explanatory stack based solution
crawler-log-folder
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n# Code\n```\nclass Solution:\n def minOperations(self, logs: List[str]) -> int:\n stack = [] \n for lg in logs:\n if lg != \'./\':\n if lg != \'../\':\n stack.append(lg)\n else:\n if stack:\n stack.pop()\n return len(stack)\n\n\n\n\n```
1
There is a **hidden** integer array `arr` that consists of `n` non-negative integers. It was encoded into another integer array `encoded` of length `n - 1`, such that `encoded[i] = arr[i] XOR arr[i + 1]`. For example, if `arr = [1,0,2,1]`, then `encoded = [1,2,3]`. You are given the `encoded` array. You are also given an integer `first`, that is the first element of `arr`, i.e. `arr[0]`. Return _the original array_ `arr`. It can be proved that the answer exists and is unique. **Example 1:** **Input:** encoded = \[1,2,3\], first = 1 **Output:** \[1,0,2,1\] **Explanation:** If arr = \[1,0,2,1\], then first = 1 and encoded = \[1 XOR 0, 0 XOR 2, 2 XOR 1\] = \[1,2,3\] **Example 2:** **Input:** encoded = \[6,2,7,3\], first = 4 **Output:** \[4,2,0,7,4\] **Constraints:** * `2 <= n <= 104` * `encoded.length == n - 1` * `0 <= encoded[i] <= 105` * `0 <= first <= 105`
Simulate the process but don’t move the pointer beyond the main folder. Simulate the process but don’t move the pointer beyond the main folder.
Simple implementing with using Stack DS
crawler-log-folder
0
1
# Intuition\nThe descriptions is leading us to use the **stack**, that follows LIFO-schema.\n\n---\n\nIf you don\'t familiar with **stack**, lets have a look at [wiki page about stack description](https://en.wikipedia.org/wiki/Stack_(abstract_data_type)).\n\n# Approach\n1. create `stack` variable, that\'ll be store all of the elelement, that aren\'t in this list `folders = [\'./\', \'../\']`\n2. iterate over all `logs` and check, if log contains `../`, it\'s time to **back to the parent folder**, if it\'s `./`, than do **NOTHING**, otherwise save this dir inside of a stack.\n3. be sure NOT to **pop from an empty stack, that causes an IndexError**\n4. **finally check HOW** many dirs are in the stack\n\n# Complexity\n- Time complexity: **O(n)** because of iterating `logs`\n\n- Space complexity: **O(n)**, in the worst case, if the folders aren\'t that list of `folders`\n\n# Code\n```\nclass Solution:\n def minOperations(self, logs: List[str]) -> int:\n stack = []\n\n for log in logs:\n if log.startswith(\'../\'):\n if stack:\n stack.pop()\n elif log.startswith(\'./\'):\n continue\n else:\n stack.append(log)\n\n return len(stack)\n```
1
The Leetcode file system keeps a log each time some user performs a _change folder_ operation. The operations are described below: * `"../ "` : Move to the parent folder of the current folder. (If you are already in the main folder, **remain in the same folder**). * `"./ "` : Remain in the same folder. * `"x/ "` : Move to the child folder named `x` (This folder is **guaranteed to always exist**). You are given a list of strings `logs` where `logs[i]` is the operation performed by the user at the `ith` step. The file system starts in the main folder, then the operations in `logs` are performed. Return _the minimum number of operations needed to go back to the main folder after the change folder operations._ **Example 1:** **Input:** logs = \[ "d1/ ", "d2/ ", "../ ", "d21/ ", "./ "\] **Output:** 2 **Explanation:** Use this change folder operation "../ " 2 times and go back to the main folder. **Example 2:** **Input:** logs = \[ "d1/ ", "d2/ ", "./ ", "d3/ ", "../ ", "d31/ "\] **Output:** 3 **Example 3:** **Input:** logs = \[ "d1/ ", "../ ", "../ ", "../ "\] **Output:** 0 **Constraints:** * `1 <= logs.length <= 103` * `2 <= logs[i].length <= 10` * `logs[i]` contains lowercase English letters, digits, `'.'`, and `'/'`. * `logs[i]` follows the format described in the statement. * Folder names consist of lowercase English letters and digits.
null
Simple implementing with using Stack DS
crawler-log-folder
0
1
# Intuition\nThe descriptions is leading us to use the **stack**, that follows LIFO-schema.\n\n---\n\nIf you don\'t familiar with **stack**, lets have a look at [wiki page about stack description](https://en.wikipedia.org/wiki/Stack_(abstract_data_type)).\n\n# Approach\n1. create `stack` variable, that\'ll be store all of the elelement, that aren\'t in this list `folders = [\'./\', \'../\']`\n2. iterate over all `logs` and check, if log contains `../`, it\'s time to **back to the parent folder**, if it\'s `./`, than do **NOTHING**, otherwise save this dir inside of a stack.\n3. be sure NOT to **pop from an empty stack, that causes an IndexError**\n4. **finally check HOW** many dirs are in the stack\n\n# Complexity\n- Time complexity: **O(n)** because of iterating `logs`\n\n- Space complexity: **O(n)**, in the worst case, if the folders aren\'t that list of `folders`\n\n# Code\n```\nclass Solution:\n def minOperations(self, logs: List[str]) -> int:\n stack = []\n\n for log in logs:\n if log.startswith(\'../\'):\n if stack:\n stack.pop()\n elif log.startswith(\'./\'):\n continue\n else:\n stack.append(log)\n\n return len(stack)\n```
1
There is a **hidden** integer array `arr` that consists of `n` non-negative integers. It was encoded into another integer array `encoded` of length `n - 1`, such that `encoded[i] = arr[i] XOR arr[i + 1]`. For example, if `arr = [1,0,2,1]`, then `encoded = [1,2,3]`. You are given the `encoded` array. You are also given an integer `first`, that is the first element of `arr`, i.e. `arr[0]`. Return _the original array_ `arr`. It can be proved that the answer exists and is unique. **Example 1:** **Input:** encoded = \[1,2,3\], first = 1 **Output:** \[1,0,2,1\] **Explanation:** If arr = \[1,0,2,1\], then first = 1 and encoded = \[1 XOR 0, 0 XOR 2, 2 XOR 1\] = \[1,2,3\] **Example 2:** **Input:** encoded = \[6,2,7,3\], first = 4 **Output:** \[4,2,0,7,4\] **Constraints:** * `2 <= n <= 104` * `encoded.length == n - 1` * `0 <= encoded[i] <= 105` * `0 <= first <= 105`
Simulate the process but don’t move the pointer beyond the main folder. Simulate the process but don’t move the pointer beyond the main folder.
Python solution with one pass
crawler-log-folder
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIterate through the logs, \n- if there are two dots and the steps is greater than zero, then step decreases by 1\n- if there is only one dot, steps doesn\' change\n- if it\'s a folder, steps increase by 1\n\n\n\n# Complexity\n- Time complexity: `O(n)`\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: `O(1)`\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python\nclass Solution:\n def minOperations(self, logs: List[str]) -> int:\n steps = 0\n for log in logs:\n if ".." in log:\n steps -= steps > 0\n elif "." in log:\n continue\n else:\n steps += 1\n return steps if steps > 0 else 0\n```\n\nOr using `match`\n\n```python\nclass Solution:\n def minOperations(self, logs: List[str]) -> int:\n steps = 0\n for log in logs:\n match log.split("/")[0]:\n case "..":\n steps -= steps > 0\n case ".":\n continue\n case d:\n steps += 1\n return steps if steps > 0 else 0\n```\n\n**Please upvote if you found if helpful.**
2
The Leetcode file system keeps a log each time some user performs a _change folder_ operation. The operations are described below: * `"../ "` : Move to the parent folder of the current folder. (If you are already in the main folder, **remain in the same folder**). * `"./ "` : Remain in the same folder. * `"x/ "` : Move to the child folder named `x` (This folder is **guaranteed to always exist**). You are given a list of strings `logs` where `logs[i]` is the operation performed by the user at the `ith` step. The file system starts in the main folder, then the operations in `logs` are performed. Return _the minimum number of operations needed to go back to the main folder after the change folder operations._ **Example 1:** **Input:** logs = \[ "d1/ ", "d2/ ", "../ ", "d21/ ", "./ "\] **Output:** 2 **Explanation:** Use this change folder operation "../ " 2 times and go back to the main folder. **Example 2:** **Input:** logs = \[ "d1/ ", "d2/ ", "./ ", "d3/ ", "../ ", "d31/ "\] **Output:** 3 **Example 3:** **Input:** logs = \[ "d1/ ", "../ ", "../ ", "../ "\] **Output:** 0 **Constraints:** * `1 <= logs.length <= 103` * `2 <= logs[i].length <= 10` * `logs[i]` contains lowercase English letters, digits, `'.'`, and `'/'`. * `logs[i]` follows the format described in the statement. * Folder names consist of lowercase English letters and digits.
null
Python solution with one pass
crawler-log-folder
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIterate through the logs, \n- if there are two dots and the steps is greater than zero, then step decreases by 1\n- if there is only one dot, steps doesn\' change\n- if it\'s a folder, steps increase by 1\n\n\n\n# Complexity\n- Time complexity: `O(n)`\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: `O(1)`\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python\nclass Solution:\n def minOperations(self, logs: List[str]) -> int:\n steps = 0\n for log in logs:\n if ".." in log:\n steps -= steps > 0\n elif "." in log:\n continue\n else:\n steps += 1\n return steps if steps > 0 else 0\n```\n\nOr using `match`\n\n```python\nclass Solution:\n def minOperations(self, logs: List[str]) -> int:\n steps = 0\n for log in logs:\n match log.split("/")[0]:\n case "..":\n steps -= steps > 0\n case ".":\n continue\n case d:\n steps += 1\n return steps if steps > 0 else 0\n```\n\n**Please upvote if you found if helpful.**
2
There is a **hidden** integer array `arr` that consists of `n` non-negative integers. It was encoded into another integer array `encoded` of length `n - 1`, such that `encoded[i] = arr[i] XOR arr[i + 1]`. For example, if `arr = [1,0,2,1]`, then `encoded = [1,2,3]`. You are given the `encoded` array. You are also given an integer `first`, that is the first element of `arr`, i.e. `arr[0]`. Return _the original array_ `arr`. It can be proved that the answer exists and is unique. **Example 1:** **Input:** encoded = \[1,2,3\], first = 1 **Output:** \[1,0,2,1\] **Explanation:** If arr = \[1,0,2,1\], then first = 1 and encoded = \[1 XOR 0, 0 XOR 2, 2 XOR 1\] = \[1,2,3\] **Example 2:** **Input:** encoded = \[6,2,7,3\], first = 4 **Output:** \[4,2,0,7,4\] **Constraints:** * `2 <= n <= 104` * `encoded.length == n - 1` * `0 <= encoded[i] <= 105` * `0 <= first <= 105`
Simulate the process but don’t move the pointer beyond the main folder. Simulate the process but don’t move the pointer beyond the main folder.
Simple Python code
crawler-log-folder
0
1
# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minOperations(self, logs: List[str]) -> int:\n stack = []\n for log in logs:\n if log == "./":\n continue\n elif log == "../":\n if stack:\n stack.pop()\n else:\n stack.append(log)\n return len(stack)\n```
1
The Leetcode file system keeps a log each time some user performs a _change folder_ operation. The operations are described below: * `"../ "` : Move to the parent folder of the current folder. (If you are already in the main folder, **remain in the same folder**). * `"./ "` : Remain in the same folder. * `"x/ "` : Move to the child folder named `x` (This folder is **guaranteed to always exist**). You are given a list of strings `logs` where `logs[i]` is the operation performed by the user at the `ith` step. The file system starts in the main folder, then the operations in `logs` are performed. Return _the minimum number of operations needed to go back to the main folder after the change folder operations._ **Example 1:** **Input:** logs = \[ "d1/ ", "d2/ ", "../ ", "d21/ ", "./ "\] **Output:** 2 **Explanation:** Use this change folder operation "../ " 2 times and go back to the main folder. **Example 2:** **Input:** logs = \[ "d1/ ", "d2/ ", "./ ", "d3/ ", "../ ", "d31/ "\] **Output:** 3 **Example 3:** **Input:** logs = \[ "d1/ ", "../ ", "../ ", "../ "\] **Output:** 0 **Constraints:** * `1 <= logs.length <= 103` * `2 <= logs[i].length <= 10` * `logs[i]` contains lowercase English letters, digits, `'.'`, and `'/'`. * `logs[i]` follows the format described in the statement. * Folder names consist of lowercase English letters and digits.
null
Simple Python code
crawler-log-folder
0
1
# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minOperations(self, logs: List[str]) -> int:\n stack = []\n for log in logs:\n if log == "./":\n continue\n elif log == "../":\n if stack:\n stack.pop()\n else:\n stack.append(log)\n return len(stack)\n```
1
There is a **hidden** integer array `arr` that consists of `n` non-negative integers. It was encoded into another integer array `encoded` of length `n - 1`, such that `encoded[i] = arr[i] XOR arr[i + 1]`. For example, if `arr = [1,0,2,1]`, then `encoded = [1,2,3]`. You are given the `encoded` array. You are also given an integer `first`, that is the first element of `arr`, i.e. `arr[0]`. Return _the original array_ `arr`. It can be proved that the answer exists and is unique. **Example 1:** **Input:** encoded = \[1,2,3\], first = 1 **Output:** \[1,0,2,1\] **Explanation:** If arr = \[1,0,2,1\], then first = 1 and encoded = \[1 XOR 0, 0 XOR 2, 2 XOR 1\] = \[1,2,3\] **Example 2:** **Input:** encoded = \[6,2,7,3\], first = 4 **Output:** \[4,2,0,7,4\] **Constraints:** * `2 <= n <= 104` * `encoded.length == n - 1` * `0 <= encoded[i] <= 105` * `0 <= first <= 105`
Simulate the process but don’t move the pointer beyond the main folder. Simulate the process but don’t move the pointer beyond the main folder.
Easy Python Solution using Stacks
crawler-log-folder
0
1
# Code\n```\nclass Solution:\n def minOperations(self, logs: List[str]) -> int:\n stack=[]\n for i in logs:\n if i=="./":\n continue\n elif stack and i=="../":\n stack.pop()\n elif i!=\'../\':\n stack.append(i)\n return len(stack)\n```
4
The Leetcode file system keeps a log each time some user performs a _change folder_ operation. The operations are described below: * `"../ "` : Move to the parent folder of the current folder. (If you are already in the main folder, **remain in the same folder**). * `"./ "` : Remain in the same folder. * `"x/ "` : Move to the child folder named `x` (This folder is **guaranteed to always exist**). You are given a list of strings `logs` where `logs[i]` is the operation performed by the user at the `ith` step. The file system starts in the main folder, then the operations in `logs` are performed. Return _the minimum number of operations needed to go back to the main folder after the change folder operations._ **Example 1:** **Input:** logs = \[ "d1/ ", "d2/ ", "../ ", "d21/ ", "./ "\] **Output:** 2 **Explanation:** Use this change folder operation "../ " 2 times and go back to the main folder. **Example 2:** **Input:** logs = \[ "d1/ ", "d2/ ", "./ ", "d3/ ", "../ ", "d31/ "\] **Output:** 3 **Example 3:** **Input:** logs = \[ "d1/ ", "../ ", "../ ", "../ "\] **Output:** 0 **Constraints:** * `1 <= logs.length <= 103` * `2 <= logs[i].length <= 10` * `logs[i]` contains lowercase English letters, digits, `'.'`, and `'/'`. * `logs[i]` follows the format described in the statement. * Folder names consist of lowercase English letters and digits.
null
Easy Python Solution using Stacks
crawler-log-folder
0
1
# Code\n```\nclass Solution:\n def minOperations(self, logs: List[str]) -> int:\n stack=[]\n for i in logs:\n if i=="./":\n continue\n elif stack and i=="../":\n stack.pop()\n elif i!=\'../\':\n stack.append(i)\n return len(stack)\n```
4
There is a **hidden** integer array `arr` that consists of `n` non-negative integers. It was encoded into another integer array `encoded` of length `n - 1`, such that `encoded[i] = arr[i] XOR arr[i + 1]`. For example, if `arr = [1,0,2,1]`, then `encoded = [1,2,3]`. You are given the `encoded` array. You are also given an integer `first`, that is the first element of `arr`, i.e. `arr[0]`. Return _the original array_ `arr`. It can be proved that the answer exists and is unique. **Example 1:** **Input:** encoded = \[1,2,3\], first = 1 **Output:** \[1,0,2,1\] **Explanation:** If arr = \[1,0,2,1\], then first = 1 and encoded = \[1 XOR 0, 0 XOR 2, 2 XOR 1\] = \[1,2,3\] **Example 2:** **Input:** encoded = \[6,2,7,3\], first = 4 **Output:** \[4,2,0,7,4\] **Constraints:** * `2 <= n <= 104` * `encoded.length == n - 1` * `0 <= encoded[i] <= 105` * `0 <= first <= 105`
Simulate the process but don’t move the pointer beyond the main folder. Simulate the process but don’t move the pointer beyond the main folder.
[Python3] straightforward
crawler-log-folder
0
1
\n```\nclass Solution:\n def minOperations(self, logs: List[str]) -> int:\n ans = 0\n for log in logs: \n if log == "./": continue\n elif log == "../": ans = max(0, ans-1) # parent directory\n else: ans += 1 # child directory \n return ans \n```
11
The Leetcode file system keeps a log each time some user performs a _change folder_ operation. The operations are described below: * `"../ "` : Move to the parent folder of the current folder. (If you are already in the main folder, **remain in the same folder**). * `"./ "` : Remain in the same folder. * `"x/ "` : Move to the child folder named `x` (This folder is **guaranteed to always exist**). You are given a list of strings `logs` where `logs[i]` is the operation performed by the user at the `ith` step. The file system starts in the main folder, then the operations in `logs` are performed. Return _the minimum number of operations needed to go back to the main folder after the change folder operations._ **Example 1:** **Input:** logs = \[ "d1/ ", "d2/ ", "../ ", "d21/ ", "./ "\] **Output:** 2 **Explanation:** Use this change folder operation "../ " 2 times and go back to the main folder. **Example 2:** **Input:** logs = \[ "d1/ ", "d2/ ", "./ ", "d3/ ", "../ ", "d31/ "\] **Output:** 3 **Example 3:** **Input:** logs = \[ "d1/ ", "../ ", "../ ", "../ "\] **Output:** 0 **Constraints:** * `1 <= logs.length <= 103` * `2 <= logs[i].length <= 10` * `logs[i]` contains lowercase English letters, digits, `'.'`, and `'/'`. * `logs[i]` follows the format described in the statement. * Folder names consist of lowercase English letters and digits.
null
[Python3] straightforward
crawler-log-folder
0
1
\n```\nclass Solution:\n def minOperations(self, logs: List[str]) -> int:\n ans = 0\n for log in logs: \n if log == "./": continue\n elif log == "../": ans = max(0, ans-1) # parent directory\n else: ans += 1 # child directory \n return ans \n```
11
There is a **hidden** integer array `arr` that consists of `n` non-negative integers. It was encoded into another integer array `encoded` of length `n - 1`, such that `encoded[i] = arr[i] XOR arr[i + 1]`. For example, if `arr = [1,0,2,1]`, then `encoded = [1,2,3]`. You are given the `encoded` array. You are also given an integer `first`, that is the first element of `arr`, i.e. `arr[0]`. Return _the original array_ `arr`. It can be proved that the answer exists and is unique. **Example 1:** **Input:** encoded = \[1,2,3\], first = 1 **Output:** \[1,0,2,1\] **Explanation:** If arr = \[1,0,2,1\], then first = 1 and encoded = \[1 XOR 0, 0 XOR 2, 2 XOR 1\] = \[1,2,3\] **Example 2:** **Input:** encoded = \[6,2,7,3\], first = 4 **Output:** \[4,2,0,7,4\] **Constraints:** * `2 <= n <= 104` * `encoded.length == n - 1` * `0 <= encoded[i] <= 105` * `0 <= first <= 105`
Simulate the process but don’t move the pointer beyond the main folder. Simulate the process but don’t move the pointer beyond the main folder.
Intuitive code and easily understandable in Python
crawler-log-folder
0
1
```\nclass Solution:\n def minOperations(self, logs: List[str]) -> int:\n res = 0\n for i in logs:\n if i == \'./\':\n continue\n elif i == \'../\':\n if res > 0:\n res -= 1\n else:\n res += 1\n return res\n```
4
The Leetcode file system keeps a log each time some user performs a _change folder_ operation. The operations are described below: * `"../ "` : Move to the parent folder of the current folder. (If you are already in the main folder, **remain in the same folder**). * `"./ "` : Remain in the same folder. * `"x/ "` : Move to the child folder named `x` (This folder is **guaranteed to always exist**). You are given a list of strings `logs` where `logs[i]` is the operation performed by the user at the `ith` step. The file system starts in the main folder, then the operations in `logs` are performed. Return _the minimum number of operations needed to go back to the main folder after the change folder operations._ **Example 1:** **Input:** logs = \[ "d1/ ", "d2/ ", "../ ", "d21/ ", "./ "\] **Output:** 2 **Explanation:** Use this change folder operation "../ " 2 times and go back to the main folder. **Example 2:** **Input:** logs = \[ "d1/ ", "d2/ ", "./ ", "d3/ ", "../ ", "d31/ "\] **Output:** 3 **Example 3:** **Input:** logs = \[ "d1/ ", "../ ", "../ ", "../ "\] **Output:** 0 **Constraints:** * `1 <= logs.length <= 103` * `2 <= logs[i].length <= 10` * `logs[i]` contains lowercase English letters, digits, `'.'`, and `'/'`. * `logs[i]` follows the format described in the statement. * Folder names consist of lowercase English letters and digits.
null
Intuitive code and easily understandable in Python
crawler-log-folder
0
1
```\nclass Solution:\n def minOperations(self, logs: List[str]) -> int:\n res = 0\n for i in logs:\n if i == \'./\':\n continue\n elif i == \'../\':\n if res > 0:\n res -= 1\n else:\n res += 1\n return res\n```
4
There is a **hidden** integer array `arr` that consists of `n` non-negative integers. It was encoded into another integer array `encoded` of length `n - 1`, such that `encoded[i] = arr[i] XOR arr[i + 1]`. For example, if `arr = [1,0,2,1]`, then `encoded = [1,2,3]`. You are given the `encoded` array. You are also given an integer `first`, that is the first element of `arr`, i.e. `arr[0]`. Return _the original array_ `arr`. It can be proved that the answer exists and is unique. **Example 1:** **Input:** encoded = \[1,2,3\], first = 1 **Output:** \[1,0,2,1\] **Explanation:** If arr = \[1,0,2,1\], then first = 1 and encoded = \[1 XOR 0, 0 XOR 2, 2 XOR 1\] = \[1,2,3\] **Example 2:** **Input:** encoded = \[6,2,7,3\], first = 4 **Output:** \[4,2,0,7,4\] **Constraints:** * `2 <= n <= 104` * `encoded.length == n - 1` * `0 <= encoded[i] <= 105` * `0 <= first <= 105`
Simulate the process but don’t move the pointer beyond the main folder. Simulate the process but don’t move the pointer beyond the main folder.
PYTHON | Super Easy python solution
crawler-log-folder
0
1
```\nclass Solution:\n def minOperations(self, logs: List[str]) -> int:\n res = 0\n \n for i in logs:\n if i == \'../\' and res > 0:\n res -= 1\n elif i != \'./\' and i != \'../\':\n res += 1\n \n return res\n```
6
The Leetcode file system keeps a log each time some user performs a _change folder_ operation. The operations are described below: * `"../ "` : Move to the parent folder of the current folder. (If you are already in the main folder, **remain in the same folder**). * `"./ "` : Remain in the same folder. * `"x/ "` : Move to the child folder named `x` (This folder is **guaranteed to always exist**). You are given a list of strings `logs` where `logs[i]` is the operation performed by the user at the `ith` step. The file system starts in the main folder, then the operations in `logs` are performed. Return _the minimum number of operations needed to go back to the main folder after the change folder operations._ **Example 1:** **Input:** logs = \[ "d1/ ", "d2/ ", "../ ", "d21/ ", "./ "\] **Output:** 2 **Explanation:** Use this change folder operation "../ " 2 times and go back to the main folder. **Example 2:** **Input:** logs = \[ "d1/ ", "d2/ ", "./ ", "d3/ ", "../ ", "d31/ "\] **Output:** 3 **Example 3:** **Input:** logs = \[ "d1/ ", "../ ", "../ ", "../ "\] **Output:** 0 **Constraints:** * `1 <= logs.length <= 103` * `2 <= logs[i].length <= 10` * `logs[i]` contains lowercase English letters, digits, `'.'`, and `'/'`. * `logs[i]` follows the format described in the statement. * Folder names consist of lowercase English letters and digits.
null
PYTHON | Super Easy python solution
crawler-log-folder
0
1
```\nclass Solution:\n def minOperations(self, logs: List[str]) -> int:\n res = 0\n \n for i in logs:\n if i == \'../\' and res > 0:\n res -= 1\n elif i != \'./\' and i != \'../\':\n res += 1\n \n return res\n```
6
There is a **hidden** integer array `arr` that consists of `n` non-negative integers. It was encoded into another integer array `encoded` of length `n - 1`, such that `encoded[i] = arr[i] XOR arr[i + 1]`. For example, if `arr = [1,0,2,1]`, then `encoded = [1,2,3]`. You are given the `encoded` array. You are also given an integer `first`, that is the first element of `arr`, i.e. `arr[0]`. Return _the original array_ `arr`. It can be proved that the answer exists and is unique. **Example 1:** **Input:** encoded = \[1,2,3\], first = 1 **Output:** \[1,0,2,1\] **Explanation:** If arr = \[1,0,2,1\], then first = 1 and encoded = \[1 XOR 0, 0 XOR 2, 2 XOR 1\] = \[1,2,3\] **Example 2:** **Input:** encoded = \[6,2,7,3\], first = 4 **Output:** \[4,2,0,7,4\] **Constraints:** * `2 <= n <= 104` * `encoded.length == n - 1` * `0 <= encoded[i] <= 105` * `0 <= first <= 105`
Simulate the process but don’t move the pointer beyond the main folder. Simulate the process but don’t move the pointer beyond the main folder.
just parse string
crawler-log-folder
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minOperations(self, logs):\n c=0\n for i in range(len(logs)):\n if logs[i][:logs[i].index(\'/\')]==\'..\':\n if c:\n c=c-1\n else:\n c=c\n elif logs[i][:logs[i].index(\'/\')]==\'.\':\n c=c\n else:\n c=c+1\n return c\n```
0
The Leetcode file system keeps a log each time some user performs a _change folder_ operation. The operations are described below: * `"../ "` : Move to the parent folder of the current folder. (If you are already in the main folder, **remain in the same folder**). * `"./ "` : Remain in the same folder. * `"x/ "` : Move to the child folder named `x` (This folder is **guaranteed to always exist**). You are given a list of strings `logs` where `logs[i]` is the operation performed by the user at the `ith` step. The file system starts in the main folder, then the operations in `logs` are performed. Return _the minimum number of operations needed to go back to the main folder after the change folder operations._ **Example 1:** **Input:** logs = \[ "d1/ ", "d2/ ", "../ ", "d21/ ", "./ "\] **Output:** 2 **Explanation:** Use this change folder operation "../ " 2 times and go back to the main folder. **Example 2:** **Input:** logs = \[ "d1/ ", "d2/ ", "./ ", "d3/ ", "../ ", "d31/ "\] **Output:** 3 **Example 3:** **Input:** logs = \[ "d1/ ", "../ ", "../ ", "../ "\] **Output:** 0 **Constraints:** * `1 <= logs.length <= 103` * `2 <= logs[i].length <= 10` * `logs[i]` contains lowercase English letters, digits, `'.'`, and `'/'`. * `logs[i]` follows the format described in the statement. * Folder names consist of lowercase English letters and digits.
null
just parse string
crawler-log-folder
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minOperations(self, logs):\n c=0\n for i in range(len(logs)):\n if logs[i][:logs[i].index(\'/\')]==\'..\':\n if c:\n c=c-1\n else:\n c=c\n elif logs[i][:logs[i].index(\'/\')]==\'.\':\n c=c\n else:\n c=c+1\n return c\n```
0
There is a **hidden** integer array `arr` that consists of `n` non-negative integers. It was encoded into another integer array `encoded` of length `n - 1`, such that `encoded[i] = arr[i] XOR arr[i + 1]`. For example, if `arr = [1,0,2,1]`, then `encoded = [1,2,3]`. You are given the `encoded` array. You are also given an integer `first`, that is the first element of `arr`, i.e. `arr[0]`. Return _the original array_ `arr`. It can be proved that the answer exists and is unique. **Example 1:** **Input:** encoded = \[1,2,3\], first = 1 **Output:** \[1,0,2,1\] **Explanation:** If arr = \[1,0,2,1\], then first = 1 and encoded = \[1 XOR 0, 0 XOR 2, 2 XOR 1\] = \[1,2,3\] **Example 2:** **Input:** encoded = \[6,2,7,3\], first = 4 **Output:** \[4,2,0,7,4\] **Constraints:** * `2 <= n <= 104` * `encoded.length == n - 1` * `0 <= encoded[i] <= 105` * `0 <= first <= 105`
Simulate the process but don’t move the pointer beyond the main folder. Simulate the process but don’t move the pointer beyond the main folder.
PYTHON3 O(N) SIMPLEST SIMULATION. BEATS 90% USERS. SIMPLE AND ELEGANT
maximum-profit-of-operating-a-centennial-wheel
0
1
```\nclass Solution:\n def minOperationsMaxProfit(self, customers: List[int], boardingCost: int, runningCost: int) -> int:\n maxProfit=-1\n ans=i=curRounds=curCustomers=rem=0\n while i<len(customers) or rem:\n if i<len(customers):\n rem+=customers[i]\n i+=1\n curRounds+=1\n if rem-4>=0:\n rem-=4\n curCustomers+=4\n else:\n curCustomers+=rem\n rem=0\n curProfit=(curCustomers*boardingCost)-(curRounds*runningCost)\n if curProfit>maxProfit:\n maxProfit=curProfit\n ans=curRounds\n return -1 if maxProfit<=0 else ans\n```
0
You are the operator of a Centennial Wheel that has **four gondolas**, and each gondola has room for **up** **to** **four people**. You have the ability to rotate the gondolas **counterclockwise**, which costs you `runningCost` dollars. You are given an array `customers` of length `n` where `customers[i]` is the number of new customers arriving just before the `ith` rotation (0-indexed). This means you **must rotate the wheel** `i` **times before the** `customers[i]` **customers arrive**. **You cannot make customers wait if there is room in the gondola**. Each customer pays `boardingCost` dollars when they board on the gondola closest to the ground and will exit once that gondola reaches the ground again. You can stop the wheel at any time, including **before** **serving** **all** **customers**. If you decide to stop serving customers, **all subsequent rotations are free** in order to get all the customers down safely. Note that if there are currently more than four customers waiting at the wheel, only four will board the gondola, and the rest will wait **for the next rotation**. Return _the minimum number of rotations you need to perform to maximize your profit._ If there is **no scenario** where the profit is positive, return `-1`. **Example 1:** **Input:** customers = \[8,3\], boardingCost = 5, runningCost = 6 **Output:** 3 **Explanation:** The numbers written on the gondolas are the number of people currently there. 1. 8 customers arrive, 4 board and 4 wait for the next gondola, the wheel rotates. Current profit is 4 \* $5 - 1 \* $6 = $14. 2. 3 customers arrive, the 4 waiting board the wheel and the other 3 wait, the wheel rotates. Current profit is 8 \* $5 - 2 \* $6 = $28. 3. The final 3 customers board the gondola, the wheel rotates. Current profit is 11 \* $5 - 3 \* $6 = $37. The highest profit was $37 after rotating the wheel 3 times. **Example 2:** **Input:** customers = \[10,9,6\], boardingCost = 6, runningCost = 4 **Output:** 7 **Explanation:** 1. 10 customers arrive, 4 board and 6 wait for the next gondola, the wheel rotates. Current profit is 4 \* $6 - 1 \* $4 = $20. 2. 9 customers arrive, 4 board and 11 wait (2 originally waiting, 9 newly waiting), the wheel rotates. Current profit is 8 \* $6 - 2 \* $4 = $40. 3. The final 6 customers arrive, 4 board and 13 wait, the wheel rotates. Current profit is 12 \* $6 - 3 \* $4 = $60. 4. 4 board and 9 wait, the wheel rotates. Current profit is 16 \* $6 - 4 \* $4 = $80. 5. 4 board and 5 wait, the wheel rotates. Current profit is 20 \* $6 - 5 \* $4 = $100. 6. 4 board and 1 waits, the wheel rotates. Current profit is 24 \* $6 - 6 \* $4 = $120. 7. 1 boards, the wheel rotates. Current profit is 25 \* $6 - 7 \* $4 = $122. The highest profit was $122 after rotating the wheel 7 times. **Example 3:** **Input:** customers = \[3,4,0,5,1\], boardingCost = 1, runningCost = 92 **Output:** -1 **Explanation:** 1. 3 customers arrive, 3 board and 0 wait, the wheel rotates. Current profit is 3 \* $1 - 1 \* $92 = -$89. 2. 4 customers arrive, 4 board and 0 wait, the wheel rotates. Current profit is 7 \* $1 - 2 \* $92 = -$177. 3. 0 customers arrive, 0 board and 0 wait, the wheel rotates. Current profit is 7 \* $1 - 3 \* $92 = -$269. 4. 5 customers arrive, 4 board and 1 waits, the wheel rotates. Current profit is 11 \* $1 - 4 \* $92 = -$357. 5. 1 customer arrives, 2 board and 0 wait, the wheel rotates. Current profit is 13 \* $1 - 5 \* $92 = -$447. The profit was never positive, so return -1. **Constraints:** * `n == customers.length` * `1 <= n <= 105` * `0 <= customers[i] <= 50` * `1 <= boardingCost, runningCost <= 100`
null
PYTHON3 O(N) SIMPLEST SIMULATION. BEATS 90% USERS. SIMPLE AND ELEGANT
maximum-profit-of-operating-a-centennial-wheel
0
1
```\nclass Solution:\n def minOperationsMaxProfit(self, customers: List[int], boardingCost: int, runningCost: int) -> int:\n maxProfit=-1\n ans=i=curRounds=curCustomers=rem=0\n while i<len(customers) or rem:\n if i<len(customers):\n rem+=customers[i]\n i+=1\n curRounds+=1\n if rem-4>=0:\n rem-=4\n curCustomers+=4\n else:\n curCustomers+=rem\n rem=0\n curProfit=(curCustomers*boardingCost)-(curRounds*runningCost)\n if curProfit>maxProfit:\n maxProfit=curProfit\n ans=curRounds\n return -1 if maxProfit<=0 else ans\n```
0
You are given the `head` of a linked list, and an integer `k`. Return _the head of the linked list after **swapping** the values of the_ `kth` _node from the beginning and the_ `kth` _node from the end (the list is **1-indexed**)._ **Example 1:** **Input:** head = \[1,2,3,4,5\], k = 2 **Output:** \[1,4,3,2,5\] **Example 2:** **Input:** head = \[7,9,6,6,7,8,3,0,9,5\], k = 5 **Output:** \[7,9,6,6,8,7,3,0,9,5\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= k <= n <= 105` * `0 <= Node.val <= 100`
Think simulation Note that the number of turns will never be more than 50 / 4 * n
Board passengers only when it is possible
maximum-profit-of-operating-a-centennial-wheel
0
1
# Intuition\nParse through all the inputs.\n\nBoard only when it is profitable (onboarding n people makes more money than it costs to run the wheel).\n\n# Code\n```\nclass Solution:\n def minOperationsMaxProfit(self, customers: List[int], boardingCost: int, runningCost: int) -> int:\n result = -1\n profit = 0\n max_profit = 0\n waiting = 0\n for i,c in enumerate(customers):\n waiting += c\n boarding = 0\n if waiting >=4:\n boarding = 4\n else:\n boarding = waiting\n if boarding*boardingCost > runningCost:\n waiting -= boarding\n profit += (boarding*boardingCost) - runningCost\n if profit > max_profit:\n max_profit = profit\n result = i+1\n q, r = divmod(waiting, 4)\n if 4*boardingCost > runningCost: result += q\n if r*boardingCost > runningCost: result += 1\n return result\n \n \n \n```
0
You are the operator of a Centennial Wheel that has **four gondolas**, and each gondola has room for **up** **to** **four people**. You have the ability to rotate the gondolas **counterclockwise**, which costs you `runningCost` dollars. You are given an array `customers` of length `n` where `customers[i]` is the number of new customers arriving just before the `ith` rotation (0-indexed). This means you **must rotate the wheel** `i` **times before the** `customers[i]` **customers arrive**. **You cannot make customers wait if there is room in the gondola**. Each customer pays `boardingCost` dollars when they board on the gondola closest to the ground and will exit once that gondola reaches the ground again. You can stop the wheel at any time, including **before** **serving** **all** **customers**. If you decide to stop serving customers, **all subsequent rotations are free** in order to get all the customers down safely. Note that if there are currently more than four customers waiting at the wheel, only four will board the gondola, and the rest will wait **for the next rotation**. Return _the minimum number of rotations you need to perform to maximize your profit._ If there is **no scenario** where the profit is positive, return `-1`. **Example 1:** **Input:** customers = \[8,3\], boardingCost = 5, runningCost = 6 **Output:** 3 **Explanation:** The numbers written on the gondolas are the number of people currently there. 1. 8 customers arrive, 4 board and 4 wait for the next gondola, the wheel rotates. Current profit is 4 \* $5 - 1 \* $6 = $14. 2. 3 customers arrive, the 4 waiting board the wheel and the other 3 wait, the wheel rotates. Current profit is 8 \* $5 - 2 \* $6 = $28. 3. The final 3 customers board the gondola, the wheel rotates. Current profit is 11 \* $5 - 3 \* $6 = $37. The highest profit was $37 after rotating the wheel 3 times. **Example 2:** **Input:** customers = \[10,9,6\], boardingCost = 6, runningCost = 4 **Output:** 7 **Explanation:** 1. 10 customers arrive, 4 board and 6 wait for the next gondola, the wheel rotates. Current profit is 4 \* $6 - 1 \* $4 = $20. 2. 9 customers arrive, 4 board and 11 wait (2 originally waiting, 9 newly waiting), the wheel rotates. Current profit is 8 \* $6 - 2 \* $4 = $40. 3. The final 6 customers arrive, 4 board and 13 wait, the wheel rotates. Current profit is 12 \* $6 - 3 \* $4 = $60. 4. 4 board and 9 wait, the wheel rotates. Current profit is 16 \* $6 - 4 \* $4 = $80. 5. 4 board and 5 wait, the wheel rotates. Current profit is 20 \* $6 - 5 \* $4 = $100. 6. 4 board and 1 waits, the wheel rotates. Current profit is 24 \* $6 - 6 \* $4 = $120. 7. 1 boards, the wheel rotates. Current profit is 25 \* $6 - 7 \* $4 = $122. The highest profit was $122 after rotating the wheel 7 times. **Example 3:** **Input:** customers = \[3,4,0,5,1\], boardingCost = 1, runningCost = 92 **Output:** -1 **Explanation:** 1. 3 customers arrive, 3 board and 0 wait, the wheel rotates. Current profit is 3 \* $1 - 1 \* $92 = -$89. 2. 4 customers arrive, 4 board and 0 wait, the wheel rotates. Current profit is 7 \* $1 - 2 \* $92 = -$177. 3. 0 customers arrive, 0 board and 0 wait, the wheel rotates. Current profit is 7 \* $1 - 3 \* $92 = -$269. 4. 5 customers arrive, 4 board and 1 waits, the wheel rotates. Current profit is 11 \* $1 - 4 \* $92 = -$357. 5. 1 customer arrives, 2 board and 0 wait, the wheel rotates. Current profit is 13 \* $1 - 5 \* $92 = -$447. The profit was never positive, so return -1. **Constraints:** * `n == customers.length` * `1 <= n <= 105` * `0 <= customers[i] <= 50` * `1 <= boardingCost, runningCost <= 100`
null
Board passengers only when it is possible
maximum-profit-of-operating-a-centennial-wheel
0
1
# Intuition\nParse through all the inputs.\n\nBoard only when it is profitable (onboarding n people makes more money than it costs to run the wheel).\n\n# Code\n```\nclass Solution:\n def minOperationsMaxProfit(self, customers: List[int], boardingCost: int, runningCost: int) -> int:\n result = -1\n profit = 0\n max_profit = 0\n waiting = 0\n for i,c in enumerate(customers):\n waiting += c\n boarding = 0\n if waiting >=4:\n boarding = 4\n else:\n boarding = waiting\n if boarding*boardingCost > runningCost:\n waiting -= boarding\n profit += (boarding*boardingCost) - runningCost\n if profit > max_profit:\n max_profit = profit\n result = i+1\n q, r = divmod(waiting, 4)\n if 4*boardingCost > runningCost: result += q\n if r*boardingCost > runningCost: result += 1\n return result\n \n \n \n```
0
You are given the `head` of a linked list, and an integer `k`. Return _the head of the linked list after **swapping** the values of the_ `kth` _node from the beginning and the_ `kth` _node from the end (the list is **1-indexed**)._ **Example 1:** **Input:** head = \[1,2,3,4,5\], k = 2 **Output:** \[1,4,3,2,5\] **Example 2:** **Input:** head = \[7,9,6,6,7,8,3,0,9,5\], k = 5 **Output:** \[7,9,6,6,8,7,3,0,9,5\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= k <= n <= 105` * `0 <= Node.val <= 100`
Think simulation Note that the number of turns will never be more than 50 / 4 * n
[LC-1599-M | Python3] A Plain Solution
maximum-profit-of-operating-a-centennial-wheel
0
1
Determine the actual length of the customers\' queue, and then use the iteration. (This approach is straightforward but not fast.)\n\n```python3 []\nclass Solution:\n def minOperationsMaxProfit(self, customers: List[int], boardingCost: int, runningCost: int) -> int:\n if 4 * boardingCost < runningCost:\n return -1\n \n more_than_once = list(filter(lambda x: x > 4, customers))\n customers += [0] * (ceil(sum(more_than_once)/4) - len(more_than_once))\n n = len(customers)\n total_profit = max_profit = min(customers[0], 4) * boardingCost - runningCost\n if n > 1:\n customers[1] += max(0, customers[0]-4)\n\n res = 1\n for i in range(1, n):\n profit = min(customers[i], 4) * boardingCost - runningCost\n total_profit += profit\n if i + 1 < n:\n customers[i+1] += max(0, customers[i]-4)\n if total_profit > max_profit:\n max_profit = total_profit\n res = i + 1\n \n return res if max_profit > 0 else -1\n```
0
You are the operator of a Centennial Wheel that has **four gondolas**, and each gondola has room for **up** **to** **four people**. You have the ability to rotate the gondolas **counterclockwise**, which costs you `runningCost` dollars. You are given an array `customers` of length `n` where `customers[i]` is the number of new customers arriving just before the `ith` rotation (0-indexed). This means you **must rotate the wheel** `i` **times before the** `customers[i]` **customers arrive**. **You cannot make customers wait if there is room in the gondola**. Each customer pays `boardingCost` dollars when they board on the gondola closest to the ground and will exit once that gondola reaches the ground again. You can stop the wheel at any time, including **before** **serving** **all** **customers**. If you decide to stop serving customers, **all subsequent rotations are free** in order to get all the customers down safely. Note that if there are currently more than four customers waiting at the wheel, only four will board the gondola, and the rest will wait **for the next rotation**. Return _the minimum number of rotations you need to perform to maximize your profit._ If there is **no scenario** where the profit is positive, return `-1`. **Example 1:** **Input:** customers = \[8,3\], boardingCost = 5, runningCost = 6 **Output:** 3 **Explanation:** The numbers written on the gondolas are the number of people currently there. 1. 8 customers arrive, 4 board and 4 wait for the next gondola, the wheel rotates. Current profit is 4 \* $5 - 1 \* $6 = $14. 2. 3 customers arrive, the 4 waiting board the wheel and the other 3 wait, the wheel rotates. Current profit is 8 \* $5 - 2 \* $6 = $28. 3. The final 3 customers board the gondola, the wheel rotates. Current profit is 11 \* $5 - 3 \* $6 = $37. The highest profit was $37 after rotating the wheel 3 times. **Example 2:** **Input:** customers = \[10,9,6\], boardingCost = 6, runningCost = 4 **Output:** 7 **Explanation:** 1. 10 customers arrive, 4 board and 6 wait for the next gondola, the wheel rotates. Current profit is 4 \* $6 - 1 \* $4 = $20. 2. 9 customers arrive, 4 board and 11 wait (2 originally waiting, 9 newly waiting), the wheel rotates. Current profit is 8 \* $6 - 2 \* $4 = $40. 3. The final 6 customers arrive, 4 board and 13 wait, the wheel rotates. Current profit is 12 \* $6 - 3 \* $4 = $60. 4. 4 board and 9 wait, the wheel rotates. Current profit is 16 \* $6 - 4 \* $4 = $80. 5. 4 board and 5 wait, the wheel rotates. Current profit is 20 \* $6 - 5 \* $4 = $100. 6. 4 board and 1 waits, the wheel rotates. Current profit is 24 \* $6 - 6 \* $4 = $120. 7. 1 boards, the wheel rotates. Current profit is 25 \* $6 - 7 \* $4 = $122. The highest profit was $122 after rotating the wheel 7 times. **Example 3:** **Input:** customers = \[3,4,0,5,1\], boardingCost = 1, runningCost = 92 **Output:** -1 **Explanation:** 1. 3 customers arrive, 3 board and 0 wait, the wheel rotates. Current profit is 3 \* $1 - 1 \* $92 = -$89. 2. 4 customers arrive, 4 board and 0 wait, the wheel rotates. Current profit is 7 \* $1 - 2 \* $92 = -$177. 3. 0 customers arrive, 0 board and 0 wait, the wheel rotates. Current profit is 7 \* $1 - 3 \* $92 = -$269. 4. 5 customers arrive, 4 board and 1 waits, the wheel rotates. Current profit is 11 \* $1 - 4 \* $92 = -$357. 5. 1 customer arrives, 2 board and 0 wait, the wheel rotates. Current profit is 13 \* $1 - 5 \* $92 = -$447. The profit was never positive, so return -1. **Constraints:** * `n == customers.length` * `1 <= n <= 105` * `0 <= customers[i] <= 50` * `1 <= boardingCost, runningCost <= 100`
null
[LC-1599-M | Python3] A Plain Solution
maximum-profit-of-operating-a-centennial-wheel
0
1
Determine the actual length of the customers\' queue, and then use the iteration. (This approach is straightforward but not fast.)\n\n```python3 []\nclass Solution:\n def minOperationsMaxProfit(self, customers: List[int], boardingCost: int, runningCost: int) -> int:\n if 4 * boardingCost < runningCost:\n return -1\n \n more_than_once = list(filter(lambda x: x > 4, customers))\n customers += [0] * (ceil(sum(more_than_once)/4) - len(more_than_once))\n n = len(customers)\n total_profit = max_profit = min(customers[0], 4) * boardingCost - runningCost\n if n > 1:\n customers[1] += max(0, customers[0]-4)\n\n res = 1\n for i in range(1, n):\n profit = min(customers[i], 4) * boardingCost - runningCost\n total_profit += profit\n if i + 1 < n:\n customers[i+1] += max(0, customers[i]-4)\n if total_profit > max_profit:\n max_profit = total_profit\n res = i + 1\n \n return res if max_profit > 0 else -1\n```
0
You are given the `head` of a linked list, and an integer `k`. Return _the head of the linked list after **swapping** the values of the_ `kth` _node from the beginning and the_ `kth` _node from the end (the list is **1-indexed**)._ **Example 1:** **Input:** head = \[1,2,3,4,5\], k = 2 **Output:** \[1,4,3,2,5\] **Example 2:** **Input:** head = \[7,9,6,6,7,8,3,0,9,5\], k = 5 **Output:** \[7,9,6,6,8,7,3,0,9,5\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= k <= n <= 105` * `0 <= Node.val <= 100`
Think simulation Note that the number of turns will never be more than 50 / 4 * n
Python (Simple Maths)
maximum-profit-of-operating-a-centennial-wheel
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minOperationsMaxProfit(self, customers, boardingCost, runningCost):\n n, profit, i, waiting, max_val, max_valAt = len(customers), 0, 0, 0, 0, 0\n\n while (waiting > 0 or i < n):\n if i < n:\n waiting += customers[i]\n \n min_val = min(4,waiting)\n profit += min_val*boardingCost - runningCost\n waiting -= min_val\n\n if profit > max_val:\n max_val = profit\n max_valAt = i + 1\n\n i += 1\n\n return max_valAt if max_valAt > 0 else -1\n\n\n\n\n\n\n \n```
0
You are the operator of a Centennial Wheel that has **four gondolas**, and each gondola has room for **up** **to** **four people**. You have the ability to rotate the gondolas **counterclockwise**, which costs you `runningCost` dollars. You are given an array `customers` of length `n` where `customers[i]` is the number of new customers arriving just before the `ith` rotation (0-indexed). This means you **must rotate the wheel** `i` **times before the** `customers[i]` **customers arrive**. **You cannot make customers wait if there is room in the gondola**. Each customer pays `boardingCost` dollars when they board on the gondola closest to the ground and will exit once that gondola reaches the ground again. You can stop the wheel at any time, including **before** **serving** **all** **customers**. If you decide to stop serving customers, **all subsequent rotations are free** in order to get all the customers down safely. Note that if there are currently more than four customers waiting at the wheel, only four will board the gondola, and the rest will wait **for the next rotation**. Return _the minimum number of rotations you need to perform to maximize your profit._ If there is **no scenario** where the profit is positive, return `-1`. **Example 1:** **Input:** customers = \[8,3\], boardingCost = 5, runningCost = 6 **Output:** 3 **Explanation:** The numbers written on the gondolas are the number of people currently there. 1. 8 customers arrive, 4 board and 4 wait for the next gondola, the wheel rotates. Current profit is 4 \* $5 - 1 \* $6 = $14. 2. 3 customers arrive, the 4 waiting board the wheel and the other 3 wait, the wheel rotates. Current profit is 8 \* $5 - 2 \* $6 = $28. 3. The final 3 customers board the gondola, the wheel rotates. Current profit is 11 \* $5 - 3 \* $6 = $37. The highest profit was $37 after rotating the wheel 3 times. **Example 2:** **Input:** customers = \[10,9,6\], boardingCost = 6, runningCost = 4 **Output:** 7 **Explanation:** 1. 10 customers arrive, 4 board and 6 wait for the next gondola, the wheel rotates. Current profit is 4 \* $6 - 1 \* $4 = $20. 2. 9 customers arrive, 4 board and 11 wait (2 originally waiting, 9 newly waiting), the wheel rotates. Current profit is 8 \* $6 - 2 \* $4 = $40. 3. The final 6 customers arrive, 4 board and 13 wait, the wheel rotates. Current profit is 12 \* $6 - 3 \* $4 = $60. 4. 4 board and 9 wait, the wheel rotates. Current profit is 16 \* $6 - 4 \* $4 = $80. 5. 4 board and 5 wait, the wheel rotates. Current profit is 20 \* $6 - 5 \* $4 = $100. 6. 4 board and 1 waits, the wheel rotates. Current profit is 24 \* $6 - 6 \* $4 = $120. 7. 1 boards, the wheel rotates. Current profit is 25 \* $6 - 7 \* $4 = $122. The highest profit was $122 after rotating the wheel 7 times. **Example 3:** **Input:** customers = \[3,4,0,5,1\], boardingCost = 1, runningCost = 92 **Output:** -1 **Explanation:** 1. 3 customers arrive, 3 board and 0 wait, the wheel rotates. Current profit is 3 \* $1 - 1 \* $92 = -$89. 2. 4 customers arrive, 4 board and 0 wait, the wheel rotates. Current profit is 7 \* $1 - 2 \* $92 = -$177. 3. 0 customers arrive, 0 board and 0 wait, the wheel rotates. Current profit is 7 \* $1 - 3 \* $92 = -$269. 4. 5 customers arrive, 4 board and 1 waits, the wheel rotates. Current profit is 11 \* $1 - 4 \* $92 = -$357. 5. 1 customer arrives, 2 board and 0 wait, the wheel rotates. Current profit is 13 \* $1 - 5 \* $92 = -$447. The profit was never positive, so return -1. **Constraints:** * `n == customers.length` * `1 <= n <= 105` * `0 <= customers[i] <= 50` * `1 <= boardingCost, runningCost <= 100`
null
Python (Simple Maths)
maximum-profit-of-operating-a-centennial-wheel
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minOperationsMaxProfit(self, customers, boardingCost, runningCost):\n n, profit, i, waiting, max_val, max_valAt = len(customers), 0, 0, 0, 0, 0\n\n while (waiting > 0 or i < n):\n if i < n:\n waiting += customers[i]\n \n min_val = min(4,waiting)\n profit += min_val*boardingCost - runningCost\n waiting -= min_val\n\n if profit > max_val:\n max_val = profit\n max_valAt = i + 1\n\n i += 1\n\n return max_valAt if max_valAt > 0 else -1\n\n\n\n\n\n\n \n```
0
You are given the `head` of a linked list, and an integer `k`. Return _the head of the linked list after **swapping** the values of the_ `kth` _node from the beginning and the_ `kth` _node from the end (the list is **1-indexed**)._ **Example 1:** **Input:** head = \[1,2,3,4,5\], k = 2 **Output:** \[1,4,3,2,5\] **Example 2:** **Input:** head = \[7,9,6,6,7,8,3,0,9,5\], k = 5 **Output:** \[7,9,6,6,8,7,3,0,9,5\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= k <= n <= 105` * `0 <= Node.val <= 100`
Think simulation Note that the number of turns will never be more than 50 / 4 * n
[Python3] simulation
maximum-profit-of-operating-a-centennial-wheel
0
1
\n```\nclass Solution:\n def minOperationsMaxProfit(self, customers: List[int], boardingCost: int, runningCost: int) -> int:\n ans = -1\n most = pnl = waiting = 0\n for i, x in enumerate(customers): \n waiting += x # more people waiting in line \n waiting -= (chg := min(4, waiting)) # boarding \n pnl += chg * boardingCost - runningCost \n if most < pnl: ans, most = i+1, pnl\n q, r = divmod(waiting, 4)\n if 4*boardingCost > runningCost: ans += q\n if r*boardingCost > runningCost: ans += 1\n return ans \n```
6
You are the operator of a Centennial Wheel that has **four gondolas**, and each gondola has room for **up** **to** **four people**. You have the ability to rotate the gondolas **counterclockwise**, which costs you `runningCost` dollars. You are given an array `customers` of length `n` where `customers[i]` is the number of new customers arriving just before the `ith` rotation (0-indexed). This means you **must rotate the wheel** `i` **times before the** `customers[i]` **customers arrive**. **You cannot make customers wait if there is room in the gondola**. Each customer pays `boardingCost` dollars when they board on the gondola closest to the ground and will exit once that gondola reaches the ground again. You can stop the wheel at any time, including **before** **serving** **all** **customers**. If you decide to stop serving customers, **all subsequent rotations are free** in order to get all the customers down safely. Note that if there are currently more than four customers waiting at the wheel, only four will board the gondola, and the rest will wait **for the next rotation**. Return _the minimum number of rotations you need to perform to maximize your profit._ If there is **no scenario** where the profit is positive, return `-1`. **Example 1:** **Input:** customers = \[8,3\], boardingCost = 5, runningCost = 6 **Output:** 3 **Explanation:** The numbers written on the gondolas are the number of people currently there. 1. 8 customers arrive, 4 board and 4 wait for the next gondola, the wheel rotates. Current profit is 4 \* $5 - 1 \* $6 = $14. 2. 3 customers arrive, the 4 waiting board the wheel and the other 3 wait, the wheel rotates. Current profit is 8 \* $5 - 2 \* $6 = $28. 3. The final 3 customers board the gondola, the wheel rotates. Current profit is 11 \* $5 - 3 \* $6 = $37. The highest profit was $37 after rotating the wheel 3 times. **Example 2:** **Input:** customers = \[10,9,6\], boardingCost = 6, runningCost = 4 **Output:** 7 **Explanation:** 1. 10 customers arrive, 4 board and 6 wait for the next gondola, the wheel rotates. Current profit is 4 \* $6 - 1 \* $4 = $20. 2. 9 customers arrive, 4 board and 11 wait (2 originally waiting, 9 newly waiting), the wheel rotates. Current profit is 8 \* $6 - 2 \* $4 = $40. 3. The final 6 customers arrive, 4 board and 13 wait, the wheel rotates. Current profit is 12 \* $6 - 3 \* $4 = $60. 4. 4 board and 9 wait, the wheel rotates. Current profit is 16 \* $6 - 4 \* $4 = $80. 5. 4 board and 5 wait, the wheel rotates. Current profit is 20 \* $6 - 5 \* $4 = $100. 6. 4 board and 1 waits, the wheel rotates. Current profit is 24 \* $6 - 6 \* $4 = $120. 7. 1 boards, the wheel rotates. Current profit is 25 \* $6 - 7 \* $4 = $122. The highest profit was $122 after rotating the wheel 7 times. **Example 3:** **Input:** customers = \[3,4,0,5,1\], boardingCost = 1, runningCost = 92 **Output:** -1 **Explanation:** 1. 3 customers arrive, 3 board and 0 wait, the wheel rotates. Current profit is 3 \* $1 - 1 \* $92 = -$89. 2. 4 customers arrive, 4 board and 0 wait, the wheel rotates. Current profit is 7 \* $1 - 2 \* $92 = -$177. 3. 0 customers arrive, 0 board and 0 wait, the wheel rotates. Current profit is 7 \* $1 - 3 \* $92 = -$269. 4. 5 customers arrive, 4 board and 1 waits, the wheel rotates. Current profit is 11 \* $1 - 4 \* $92 = -$357. 5. 1 customer arrives, 2 board and 0 wait, the wheel rotates. Current profit is 13 \* $1 - 5 \* $92 = -$447. The profit was never positive, so return -1. **Constraints:** * `n == customers.length` * `1 <= n <= 105` * `0 <= customers[i] <= 50` * `1 <= boardingCost, runningCost <= 100`
null
[Python3] simulation
maximum-profit-of-operating-a-centennial-wheel
0
1
\n```\nclass Solution:\n def minOperationsMaxProfit(self, customers: List[int], boardingCost: int, runningCost: int) -> int:\n ans = -1\n most = pnl = waiting = 0\n for i, x in enumerate(customers): \n waiting += x # more people waiting in line \n waiting -= (chg := min(4, waiting)) # boarding \n pnl += chg * boardingCost - runningCost \n if most < pnl: ans, most = i+1, pnl\n q, r = divmod(waiting, 4)\n if 4*boardingCost > runningCost: ans += q\n if r*boardingCost > runningCost: ans += 1\n return ans \n```
6
You are given the `head` of a linked list, and an integer `k`. Return _the head of the linked list after **swapping** the values of the_ `kth` _node from the beginning and the_ `kth` _node from the end (the list is **1-indexed**)._ **Example 1:** **Input:** head = \[1,2,3,4,5\], k = 2 **Output:** \[1,4,3,2,5\] **Example 2:** **Input:** head = \[7,9,6,6,7,8,3,0,9,5\], k = 5 **Output:** \[7,9,6,6,8,7,3,0,9,5\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= k <= n <= 105` * `0 <= Node.val <= 100`
Think simulation Note that the number of turns will never be more than 50 / 4 * n
Python [Simulation]
maximum-profit-of-operating-a-centennial-wheel
0
1
```\nclass Solution:\n def minOperationsMaxProfit(self, arr: List[int], boardingCost : int, runningCost : int) -> int:\n # Dividing people in the groups of <=4\n grps = []\n # length of customers array\n n = len(arr)\n # rem--> number of people waiting\n rem = 0\n \n # traversing the customers array\n for i in range(n):\n # total number of people available right now \n avail = arr[i]+rem\n # number of available people >=4 then append grp of 4 and update remaining [rem]\n if avail>=4:\n avail-=4\n grps.append(4)\n rem = avail\n # number of available people <4 then make group of available people and update remaining [rem=0]\n else:\n rem = 0\n grps.append(avail)\n \n # make groups of 4 until remaining >=4 otherwise make <4 and break\n while rem>0:\n if rem>=4:\n rem-=4\n grps.append(4)\n else:\n grps.append(rem)\n rem = 0\n \n # mex--> represents maximum profit\n mex = -10**10\n # cost--> represents current total cost\n cost = 0\n # ind --> represents rotation number\n ind = 0\n for i in range(len(grps)):\n # calculate net cost till now\n cost+= boardingCost*grps[i]-runningCost\n # upadte max profit and rotation number\n if mex<cost:\n mex = max(mex,cost)\n ind = i+1\n # max profit< 0\n if mex<0:\n return -1\n # return rotation number\n return ind\n \n```
4
You are the operator of a Centennial Wheel that has **four gondolas**, and each gondola has room for **up** **to** **four people**. You have the ability to rotate the gondolas **counterclockwise**, which costs you `runningCost` dollars. You are given an array `customers` of length `n` where `customers[i]` is the number of new customers arriving just before the `ith` rotation (0-indexed). This means you **must rotate the wheel** `i` **times before the** `customers[i]` **customers arrive**. **You cannot make customers wait if there is room in the gondola**. Each customer pays `boardingCost` dollars when they board on the gondola closest to the ground and will exit once that gondola reaches the ground again. You can stop the wheel at any time, including **before** **serving** **all** **customers**. If you decide to stop serving customers, **all subsequent rotations are free** in order to get all the customers down safely. Note that if there are currently more than four customers waiting at the wheel, only four will board the gondola, and the rest will wait **for the next rotation**. Return _the minimum number of rotations you need to perform to maximize your profit._ If there is **no scenario** where the profit is positive, return `-1`. **Example 1:** **Input:** customers = \[8,3\], boardingCost = 5, runningCost = 6 **Output:** 3 **Explanation:** The numbers written on the gondolas are the number of people currently there. 1. 8 customers arrive, 4 board and 4 wait for the next gondola, the wheel rotates. Current profit is 4 \* $5 - 1 \* $6 = $14. 2. 3 customers arrive, the 4 waiting board the wheel and the other 3 wait, the wheel rotates. Current profit is 8 \* $5 - 2 \* $6 = $28. 3. The final 3 customers board the gondola, the wheel rotates. Current profit is 11 \* $5 - 3 \* $6 = $37. The highest profit was $37 after rotating the wheel 3 times. **Example 2:** **Input:** customers = \[10,9,6\], boardingCost = 6, runningCost = 4 **Output:** 7 **Explanation:** 1. 10 customers arrive, 4 board and 6 wait for the next gondola, the wheel rotates. Current profit is 4 \* $6 - 1 \* $4 = $20. 2. 9 customers arrive, 4 board and 11 wait (2 originally waiting, 9 newly waiting), the wheel rotates. Current profit is 8 \* $6 - 2 \* $4 = $40. 3. The final 6 customers arrive, 4 board and 13 wait, the wheel rotates. Current profit is 12 \* $6 - 3 \* $4 = $60. 4. 4 board and 9 wait, the wheel rotates. Current profit is 16 \* $6 - 4 \* $4 = $80. 5. 4 board and 5 wait, the wheel rotates. Current profit is 20 \* $6 - 5 \* $4 = $100. 6. 4 board and 1 waits, the wheel rotates. Current profit is 24 \* $6 - 6 \* $4 = $120. 7. 1 boards, the wheel rotates. Current profit is 25 \* $6 - 7 \* $4 = $122. The highest profit was $122 after rotating the wheel 7 times. **Example 3:** **Input:** customers = \[3,4,0,5,1\], boardingCost = 1, runningCost = 92 **Output:** -1 **Explanation:** 1. 3 customers arrive, 3 board and 0 wait, the wheel rotates. Current profit is 3 \* $1 - 1 \* $92 = -$89. 2. 4 customers arrive, 4 board and 0 wait, the wheel rotates. Current profit is 7 \* $1 - 2 \* $92 = -$177. 3. 0 customers arrive, 0 board and 0 wait, the wheel rotates. Current profit is 7 \* $1 - 3 \* $92 = -$269. 4. 5 customers arrive, 4 board and 1 waits, the wheel rotates. Current profit is 11 \* $1 - 4 \* $92 = -$357. 5. 1 customer arrives, 2 board and 0 wait, the wheel rotates. Current profit is 13 \* $1 - 5 \* $92 = -$447. The profit was never positive, so return -1. **Constraints:** * `n == customers.length` * `1 <= n <= 105` * `0 <= customers[i] <= 50` * `1 <= boardingCost, runningCost <= 100`
null
Python [Simulation]
maximum-profit-of-operating-a-centennial-wheel
0
1
```\nclass Solution:\n def minOperationsMaxProfit(self, arr: List[int], boardingCost : int, runningCost : int) -> int:\n # Dividing people in the groups of <=4\n grps = []\n # length of customers array\n n = len(arr)\n # rem--> number of people waiting\n rem = 0\n \n # traversing the customers array\n for i in range(n):\n # total number of people available right now \n avail = arr[i]+rem\n # number of available people >=4 then append grp of 4 and update remaining [rem]\n if avail>=4:\n avail-=4\n grps.append(4)\n rem = avail\n # number of available people <4 then make group of available people and update remaining [rem=0]\n else:\n rem = 0\n grps.append(avail)\n \n # make groups of 4 until remaining >=4 otherwise make <4 and break\n while rem>0:\n if rem>=4:\n rem-=4\n grps.append(4)\n else:\n grps.append(rem)\n rem = 0\n \n # mex--> represents maximum profit\n mex = -10**10\n # cost--> represents current total cost\n cost = 0\n # ind --> represents rotation number\n ind = 0\n for i in range(len(grps)):\n # calculate net cost till now\n cost+= boardingCost*grps[i]-runningCost\n # upadte max profit and rotation number\n if mex<cost:\n mex = max(mex,cost)\n ind = i+1\n # max profit< 0\n if mex<0:\n return -1\n # return rotation number\n return ind\n \n```
4
You are given the `head` of a linked list, and an integer `k`. Return _the head of the linked list after **swapping** the values of the_ `kth` _node from the beginning and the_ `kth` _node from the end (the list is **1-indexed**)._ **Example 1:** **Input:** head = \[1,2,3,4,5\], k = 2 **Output:** \[1,4,3,2,5\] **Example 2:** **Input:** head = \[7,9,6,6,7,8,3,0,9,5\], k = 5 **Output:** \[7,9,6,6,8,7,3,0,9,5\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= k <= n <= 105` * `0 <= Node.val <= 100`
Think simulation Note that the number of turns will never be more than 50 / 4 * n
Python O(n) Solution, faster than 100%
maximum-profit-of-operating-a-centennial-wheel
0
1
**First Observation:** If `boardingCost * 4 <= runningCost`, there is no way to make profit, so return `-1` \n \n**Second Observation**: Instead of looping with increment of 4 per cycle, if we can directly calculate number of rounds for the given number of *waiting* customers, we can save a lot of time.\nLet\'s say there are 18 customers, so number of rounds = `18//4 = 4`, so instead of looping 4 times we can directly update our *rotation count*. But what will be the *waiting count* now? Is it 2?\n\n**Third Observation**: Continuing with the above example, by the time we complete our 4 rounds, more customers might have come, so our *waiting count won\'t be 2*.\n\n**Fourth Observation**: We can handle `customers[i : j]` at once using the above technique only iff, *waiting customers* till `j` is greater than minimum number of *waiting customers for index j*.\nFor Example, `[6, 2, 1, 1, 8, 3]`\nHere for index 0, `minimum waiting customers = 4` and `waiting customers = 6` , since `6 > 4`, so we can include\n\nFor index 1, `minimum waiting customers = 4+4 = 8` and `waiting customers = 6+2 = 8` so we can include. Remember we are just looking upto which index we can handle at once, we haven\'t handled them yet.\n\nFor index 2 `minimum waiting customers = 4+4+4 = 12` and `waiting customers = 6+2+1 = 9`, since `9 < 12` we will stop here and handle cases upto index 2, i.e, `[6 ,2, 1]`\nWhich will be 2 rounds with 4 passengers each and 1 more round with 1 passenger.\n\nFor index 3, we will reset, `minimum waiting customers = 4` and `waiting customers = 1`, since `1 < 4`, we will handle it\n\nFor index 4, we will reset, `minimum waiting customers = 4` and `waiting customers = 8`, since `8 > 4`, we will include it\n\nFor index 5, `minimum waiting customers = 4+4` and `waiting customers = 8+3`, since `11 > 4`, we will include it\n\nSince customer list is over, we will now handle everything.\n\nMake sure to calculate **profit** whenever you handle customers and update accordingly.\n\n```python\nclass Solution:\n def minOperationsMaxProfit(self, customers: List[int], boardingCost: int, runningCost: int) -> int:\n\t\t# Our First obsevation\n if boardingCost*4 <= runningCost: return -1\n \n n = len(customers)\n count = 0 # To keep track of number of rounds\n max_count = 0 # To keep track of round where we had maximum profit\n profit = 0 # Profit till now\n max_profit = 0 # Maximum Profit till now\n i = 0 # Index of customer list\n while i < n:\n wait = 0 # We will always start with 0 waiting customers\n min_wait = 0 # Minimum waiting count to include\n\t\t\t\n\t\t\t# Include all customers[i] until wait >= min_wait\n while i < n and wait >= min_wait:\n wait += customers[i]\n min_wait += 4\n i += 1\n\t\t\t\t\n\t\t\t# Calcuate number of rounds and update count and profit\n rounds = wait//4\n count += rounds\n profit += rounds*(4*boardingCost - runningCost)\n\t\t\t\n\t\t\t# Update max_profit and max_count if required\n if profit > max_profit:\n max_profit = profit\n max_count = count\n \n\t\t\t# Update waiting customer count\n wait %= 4\n\t\t\t\n\t\t\t# If some passengers are still waiting, do one more round\n if wait > 0 or rounds == 0:\n count += 1\n profit += wait*boardingCost - runningCost\n wait = 0 # No more passengers are waiting, for sure\n\t\t\t\t# Update max_profit and max_count if required\n if profit > max_profit:\n max_profit = profit\n max_count = count \n\n\t\t# If max_count is still 0, then our wheel hasn\'t moved at all\n\t\t# Return -1 in this case, otherwise return max_count\n return max_count if max_count else -1\n```\n\n**Submission details**: Runtime: 900 ms, faster than 100.00% of Python3 online submissions for Maximum Profit of Operating a Centennial Wheel.\nMemory Usage: 17.8 MB, less than 29.09% of Python3 online submissions for Maximum Profit of Operating a Centennial Wheel.\n\nHope it helps you :)
2
You are the operator of a Centennial Wheel that has **four gondolas**, and each gondola has room for **up** **to** **four people**. You have the ability to rotate the gondolas **counterclockwise**, which costs you `runningCost` dollars. You are given an array `customers` of length `n` where `customers[i]` is the number of new customers arriving just before the `ith` rotation (0-indexed). This means you **must rotate the wheel** `i` **times before the** `customers[i]` **customers arrive**. **You cannot make customers wait if there is room in the gondola**. Each customer pays `boardingCost` dollars when they board on the gondola closest to the ground and will exit once that gondola reaches the ground again. You can stop the wheel at any time, including **before** **serving** **all** **customers**. If you decide to stop serving customers, **all subsequent rotations are free** in order to get all the customers down safely. Note that if there are currently more than four customers waiting at the wheel, only four will board the gondola, and the rest will wait **for the next rotation**. Return _the minimum number of rotations you need to perform to maximize your profit._ If there is **no scenario** where the profit is positive, return `-1`. **Example 1:** **Input:** customers = \[8,3\], boardingCost = 5, runningCost = 6 **Output:** 3 **Explanation:** The numbers written on the gondolas are the number of people currently there. 1. 8 customers arrive, 4 board and 4 wait for the next gondola, the wheel rotates. Current profit is 4 \* $5 - 1 \* $6 = $14. 2. 3 customers arrive, the 4 waiting board the wheel and the other 3 wait, the wheel rotates. Current profit is 8 \* $5 - 2 \* $6 = $28. 3. The final 3 customers board the gondola, the wheel rotates. Current profit is 11 \* $5 - 3 \* $6 = $37. The highest profit was $37 after rotating the wheel 3 times. **Example 2:** **Input:** customers = \[10,9,6\], boardingCost = 6, runningCost = 4 **Output:** 7 **Explanation:** 1. 10 customers arrive, 4 board and 6 wait for the next gondola, the wheel rotates. Current profit is 4 \* $6 - 1 \* $4 = $20. 2. 9 customers arrive, 4 board and 11 wait (2 originally waiting, 9 newly waiting), the wheel rotates. Current profit is 8 \* $6 - 2 \* $4 = $40. 3. The final 6 customers arrive, 4 board and 13 wait, the wheel rotates. Current profit is 12 \* $6 - 3 \* $4 = $60. 4. 4 board and 9 wait, the wheel rotates. Current profit is 16 \* $6 - 4 \* $4 = $80. 5. 4 board and 5 wait, the wheel rotates. Current profit is 20 \* $6 - 5 \* $4 = $100. 6. 4 board and 1 waits, the wheel rotates. Current profit is 24 \* $6 - 6 \* $4 = $120. 7. 1 boards, the wheel rotates. Current profit is 25 \* $6 - 7 \* $4 = $122. The highest profit was $122 after rotating the wheel 7 times. **Example 3:** **Input:** customers = \[3,4,0,5,1\], boardingCost = 1, runningCost = 92 **Output:** -1 **Explanation:** 1. 3 customers arrive, 3 board and 0 wait, the wheel rotates. Current profit is 3 \* $1 - 1 \* $92 = -$89. 2. 4 customers arrive, 4 board and 0 wait, the wheel rotates. Current profit is 7 \* $1 - 2 \* $92 = -$177. 3. 0 customers arrive, 0 board and 0 wait, the wheel rotates. Current profit is 7 \* $1 - 3 \* $92 = -$269. 4. 5 customers arrive, 4 board and 1 waits, the wheel rotates. Current profit is 11 \* $1 - 4 \* $92 = -$357. 5. 1 customer arrives, 2 board and 0 wait, the wheel rotates. Current profit is 13 \* $1 - 5 \* $92 = -$447. The profit was never positive, so return -1. **Constraints:** * `n == customers.length` * `1 <= n <= 105` * `0 <= customers[i] <= 50` * `1 <= boardingCost, runningCost <= 100`
null
Python O(n) Solution, faster than 100%
maximum-profit-of-operating-a-centennial-wheel
0
1
**First Observation:** If `boardingCost * 4 <= runningCost`, there is no way to make profit, so return `-1` \n \n**Second Observation**: Instead of looping with increment of 4 per cycle, if we can directly calculate number of rounds for the given number of *waiting* customers, we can save a lot of time.\nLet\'s say there are 18 customers, so number of rounds = `18//4 = 4`, so instead of looping 4 times we can directly update our *rotation count*. But what will be the *waiting count* now? Is it 2?\n\n**Third Observation**: Continuing with the above example, by the time we complete our 4 rounds, more customers might have come, so our *waiting count won\'t be 2*.\n\n**Fourth Observation**: We can handle `customers[i : j]` at once using the above technique only iff, *waiting customers* till `j` is greater than minimum number of *waiting customers for index j*.\nFor Example, `[6, 2, 1, 1, 8, 3]`\nHere for index 0, `minimum waiting customers = 4` and `waiting customers = 6` , since `6 > 4`, so we can include\n\nFor index 1, `minimum waiting customers = 4+4 = 8` and `waiting customers = 6+2 = 8` so we can include. Remember we are just looking upto which index we can handle at once, we haven\'t handled them yet.\n\nFor index 2 `minimum waiting customers = 4+4+4 = 12` and `waiting customers = 6+2+1 = 9`, since `9 < 12` we will stop here and handle cases upto index 2, i.e, `[6 ,2, 1]`\nWhich will be 2 rounds with 4 passengers each and 1 more round with 1 passenger.\n\nFor index 3, we will reset, `minimum waiting customers = 4` and `waiting customers = 1`, since `1 < 4`, we will handle it\n\nFor index 4, we will reset, `minimum waiting customers = 4` and `waiting customers = 8`, since `8 > 4`, we will include it\n\nFor index 5, `minimum waiting customers = 4+4` and `waiting customers = 8+3`, since `11 > 4`, we will include it\n\nSince customer list is over, we will now handle everything.\n\nMake sure to calculate **profit** whenever you handle customers and update accordingly.\n\n```python\nclass Solution:\n def minOperationsMaxProfit(self, customers: List[int], boardingCost: int, runningCost: int) -> int:\n\t\t# Our First obsevation\n if boardingCost*4 <= runningCost: return -1\n \n n = len(customers)\n count = 0 # To keep track of number of rounds\n max_count = 0 # To keep track of round where we had maximum profit\n profit = 0 # Profit till now\n max_profit = 0 # Maximum Profit till now\n i = 0 # Index of customer list\n while i < n:\n wait = 0 # We will always start with 0 waiting customers\n min_wait = 0 # Minimum waiting count to include\n\t\t\t\n\t\t\t# Include all customers[i] until wait >= min_wait\n while i < n and wait >= min_wait:\n wait += customers[i]\n min_wait += 4\n i += 1\n\t\t\t\t\n\t\t\t# Calcuate number of rounds and update count and profit\n rounds = wait//4\n count += rounds\n profit += rounds*(4*boardingCost - runningCost)\n\t\t\t\n\t\t\t# Update max_profit and max_count if required\n if profit > max_profit:\n max_profit = profit\n max_count = count\n \n\t\t\t# Update waiting customer count\n wait %= 4\n\t\t\t\n\t\t\t# If some passengers are still waiting, do one more round\n if wait > 0 or rounds == 0:\n count += 1\n profit += wait*boardingCost - runningCost\n wait = 0 # No more passengers are waiting, for sure\n\t\t\t\t# Update max_profit and max_count if required\n if profit > max_profit:\n max_profit = profit\n max_count = count \n\n\t\t# If max_count is still 0, then our wheel hasn\'t moved at all\n\t\t# Return -1 in this case, otherwise return max_count\n return max_count if max_count else -1\n```\n\n**Submission details**: Runtime: 900 ms, faster than 100.00% of Python3 online submissions for Maximum Profit of Operating a Centennial Wheel.\nMemory Usage: 17.8 MB, less than 29.09% of Python3 online submissions for Maximum Profit of Operating a Centennial Wheel.\n\nHope it helps you :)
2
You are given the `head` of a linked list, and an integer `k`. Return _the head of the linked list after **swapping** the values of the_ `kth` _node from the beginning and the_ `kth` _node from the end (the list is **1-indexed**)._ **Example 1:** **Input:** head = \[1,2,3,4,5\], k = 2 **Output:** \[1,4,3,2,5\] **Example 2:** **Input:** head = \[7,9,6,6,7,8,3,0,9,5\], k = 5 **Output:** \[7,9,6,6,8,7,3,0,9,5\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= k <= n <= 105` * `0 <= Node.val <= 100`
Think simulation Note that the number of turns will never be more than 50 / 4 * n
[Python 3] simulation clean code
maximum-profit-of-operating-a-centennial-wheel
0
1
long code but faster because of less Comparison\'s and less variables used:\n\n\tclass Solution:\n\t\tdef minOperationsMaxProfit(self, customers: List[int], boardingCost: int, runningCost: int) -> int:\n\t\t\tmax_profit=Profit=curr=0\n\t\t\tmax_profit_rotation=-1\n\t\t\tfor i,x in enumerate(customers):\n\t\t\t\tcurr+=x\n\t\t\t\tchange=min(curr,4)\n\t\t\t\tcurr-=change\n\t\t\t\tProfit+=change*boardingCost-runningCost\n\t\t\t\tif Profit>max_profit:\n\t\t\t\t\tmax_profit=Profit\n\t\t\t\t\tmax_profit_rotation=i+1\n\n\t\t\ta,b=curr//4,curr%4\n\t\t\tmax_profit_rotation+=a if (4*boardingCost-runningCost)>0 else 0\n\t\t\tmax_profit_rotation+=1 if (b*boardingCost-runningCost)>0 else 0\n\t\t\treturn max_profit_rotation\n\t\t\t\nShort code but with some Extra comparison:\n\n\t\n\tclass Solution:\n\t\tdef minOperationsMaxProfit(self, customers: List[int], boardingCost: int, runningCost: int) -> int:\n\t\t\tmax_profit=Profit=t=curr=0\n\t\t\tmax_profit_rotation=-1\n\t\t\ti,n=0,len(customers)\n\t\t\twhile i<n or curr:\n\t\t\t\tcurr+=customers[i] if i<n else 0\n\t\t\t\tProfit+=min(4,curr)*boardingCost-runningCost\n\t\t\t\tt+=1\n\t\t\t\tif Profit>max_profit:\n\t\t\t\t\tmax_profit=Profit\n\t\t\t\t\tmax_profit_rotation=t\n\t\t\t\tcurr-=min(4,curr)\n\t\t\t\ti+=1\n\t\t\treturn max_profit_rotation\n\t\t\t\n
0
You are the operator of a Centennial Wheel that has **four gondolas**, and each gondola has room for **up** **to** **four people**. You have the ability to rotate the gondolas **counterclockwise**, which costs you `runningCost` dollars. You are given an array `customers` of length `n` where `customers[i]` is the number of new customers arriving just before the `ith` rotation (0-indexed). This means you **must rotate the wheel** `i` **times before the** `customers[i]` **customers arrive**. **You cannot make customers wait if there is room in the gondola**. Each customer pays `boardingCost` dollars when they board on the gondola closest to the ground and will exit once that gondola reaches the ground again. You can stop the wheel at any time, including **before** **serving** **all** **customers**. If you decide to stop serving customers, **all subsequent rotations are free** in order to get all the customers down safely. Note that if there are currently more than four customers waiting at the wheel, only four will board the gondola, and the rest will wait **for the next rotation**. Return _the minimum number of rotations you need to perform to maximize your profit._ If there is **no scenario** where the profit is positive, return `-1`. **Example 1:** **Input:** customers = \[8,3\], boardingCost = 5, runningCost = 6 **Output:** 3 **Explanation:** The numbers written on the gondolas are the number of people currently there. 1. 8 customers arrive, 4 board and 4 wait for the next gondola, the wheel rotates. Current profit is 4 \* $5 - 1 \* $6 = $14. 2. 3 customers arrive, the 4 waiting board the wheel and the other 3 wait, the wheel rotates. Current profit is 8 \* $5 - 2 \* $6 = $28. 3. The final 3 customers board the gondola, the wheel rotates. Current profit is 11 \* $5 - 3 \* $6 = $37. The highest profit was $37 after rotating the wheel 3 times. **Example 2:** **Input:** customers = \[10,9,6\], boardingCost = 6, runningCost = 4 **Output:** 7 **Explanation:** 1. 10 customers arrive, 4 board and 6 wait for the next gondola, the wheel rotates. Current profit is 4 \* $6 - 1 \* $4 = $20. 2. 9 customers arrive, 4 board and 11 wait (2 originally waiting, 9 newly waiting), the wheel rotates. Current profit is 8 \* $6 - 2 \* $4 = $40. 3. The final 6 customers arrive, 4 board and 13 wait, the wheel rotates. Current profit is 12 \* $6 - 3 \* $4 = $60. 4. 4 board and 9 wait, the wheel rotates. Current profit is 16 \* $6 - 4 \* $4 = $80. 5. 4 board and 5 wait, the wheel rotates. Current profit is 20 \* $6 - 5 \* $4 = $100. 6. 4 board and 1 waits, the wheel rotates. Current profit is 24 \* $6 - 6 \* $4 = $120. 7. 1 boards, the wheel rotates. Current profit is 25 \* $6 - 7 \* $4 = $122. The highest profit was $122 after rotating the wheel 7 times. **Example 3:** **Input:** customers = \[3,4,0,5,1\], boardingCost = 1, runningCost = 92 **Output:** -1 **Explanation:** 1. 3 customers arrive, 3 board and 0 wait, the wheel rotates. Current profit is 3 \* $1 - 1 \* $92 = -$89. 2. 4 customers arrive, 4 board and 0 wait, the wheel rotates. Current profit is 7 \* $1 - 2 \* $92 = -$177. 3. 0 customers arrive, 0 board and 0 wait, the wheel rotates. Current profit is 7 \* $1 - 3 \* $92 = -$269. 4. 5 customers arrive, 4 board and 1 waits, the wheel rotates. Current profit is 11 \* $1 - 4 \* $92 = -$357. 5. 1 customer arrives, 2 board and 0 wait, the wheel rotates. Current profit is 13 \* $1 - 5 \* $92 = -$447. The profit was never positive, so return -1. **Constraints:** * `n == customers.length` * `1 <= n <= 105` * `0 <= customers[i] <= 50` * `1 <= boardingCost, runningCost <= 100`
null
[Python 3] simulation clean code
maximum-profit-of-operating-a-centennial-wheel
0
1
long code but faster because of less Comparison\'s and less variables used:\n\n\tclass Solution:\n\t\tdef minOperationsMaxProfit(self, customers: List[int], boardingCost: int, runningCost: int) -> int:\n\t\t\tmax_profit=Profit=curr=0\n\t\t\tmax_profit_rotation=-1\n\t\t\tfor i,x in enumerate(customers):\n\t\t\t\tcurr+=x\n\t\t\t\tchange=min(curr,4)\n\t\t\t\tcurr-=change\n\t\t\t\tProfit+=change*boardingCost-runningCost\n\t\t\t\tif Profit>max_profit:\n\t\t\t\t\tmax_profit=Profit\n\t\t\t\t\tmax_profit_rotation=i+1\n\n\t\t\ta,b=curr//4,curr%4\n\t\t\tmax_profit_rotation+=a if (4*boardingCost-runningCost)>0 else 0\n\t\t\tmax_profit_rotation+=1 if (b*boardingCost-runningCost)>0 else 0\n\t\t\treturn max_profit_rotation\n\t\t\t\nShort code but with some Extra comparison:\n\n\t\n\tclass Solution:\n\t\tdef minOperationsMaxProfit(self, customers: List[int], boardingCost: int, runningCost: int) -> int:\n\t\t\tmax_profit=Profit=t=curr=0\n\t\t\tmax_profit_rotation=-1\n\t\t\ti,n=0,len(customers)\n\t\t\twhile i<n or curr:\n\t\t\t\tcurr+=customers[i] if i<n else 0\n\t\t\t\tProfit+=min(4,curr)*boardingCost-runningCost\n\t\t\t\tt+=1\n\t\t\t\tif Profit>max_profit:\n\t\t\t\t\tmax_profit=Profit\n\t\t\t\t\tmax_profit_rotation=t\n\t\t\t\tcurr-=min(4,curr)\n\t\t\t\ti+=1\n\t\t\treturn max_profit_rotation\n\t\t\t\n
0
You are given the `head` of a linked list, and an integer `k`. Return _the head of the linked list after **swapping** the values of the_ `kth` _node from the beginning and the_ `kth` _node from the end (the list is **1-indexed**)._ **Example 1:** **Input:** head = \[1,2,3,4,5\], k = 2 **Output:** \[1,4,3,2,5\] **Example 2:** **Input:** head = \[7,9,6,6,7,8,3,0,9,5\], k = 5 **Output:** \[7,9,6,6,8,7,3,0,9,5\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= k <= n <= 105` * `0 <= Node.val <= 100`
Think simulation Note that the number of turns will never be more than 50 / 4 * n
BEATS 95.00%! | Python3 Fast Easy Solution Explained
throne-inheritance
0
1
The explanation\'s in the code comments.\n# Code\n```\nclass ThroneInheritance:\n def __init__(self, kingName: str):\n # This is equivalent to the root node in a tree.\n self.kingName = kingName\n # Since we know that all family members\' names are distinct,\n # (no two names are the same), we can use a hash table.\n # Anyone who has descendants is a "key" in this hash table.\n self.ht = {kingName: []}\n # Keep track of who dies.\n self.deaths = set()\n\n def birth(self, parentName: str, childName: str) -> None:\n # Updates the family tree.\n if parentName not in self.ht:\n self.ht[parentName] = []\n self.ht[parentName].append(childName)\n\n def death(self, name: str) -> None:\n # Updates who dies.\n self.deaths.add(name)\n\n def getInheritanceOrder(self) -> List[str]:\n inheritanceOrder = []\n stack = [self.kingName]\n name = ""\n # Traverses the family tree.\n while len(stack) > 0:\n # Get the current name.\n name = stack.pop()\n # Add the person to the inheritance order if\n # he or she is still alive.\n if name not in self.deaths:\n inheritanceOrder.append(name)\n # Add the person\'s descendants to the stack in\n # reverse order if they exist.\n if name in self.ht:\n for i in range(len(self.ht[name])-1, -1, -1):\n stack.append(self.ht[name][i])\n return inheritanceOrder\n\n```
0
A kingdom consists of a king, his children, his grandchildren, and so on. Every once in a while, someone in the family dies or a child is born. The kingdom has a well-defined order of inheritance that consists of the king as the first member. Let's define the recursive function `Successor(x, curOrder)`, which given a person `x` and the inheritance order so far, returns who should be the next person after `x` in the order of inheritance. Successor(x, curOrder): if x has no children or all of x's children are in curOrder: if x is the king return null else return Successor(x's parent, curOrder) else return x's oldest child who's not in curOrder For example, assume we have a kingdom that consists of the king, his children Alice and Bob (Alice is older than Bob), and finally Alice's son Jack. 1. In the beginning, `curOrder` will be `[ "king "]`. 2. Calling `Successor(king, curOrder)` will return Alice, so we append to `curOrder` to get `[ "king ", "Alice "]`. 3. Calling `Successor(Alice, curOrder)` will return Jack, so we append to `curOrder` to get `[ "king ", "Alice ", "Jack "]`. 4. Calling `Successor(Jack, curOrder)` will return Bob, so we append to `curOrder` to get `[ "king ", "Alice ", "Jack ", "Bob "]`. 5. Calling `Successor(Bob, curOrder)` will return `null`. Thus the order of inheritance will be `[ "king ", "Alice ", "Jack ", "Bob "]`. Using the above function, we can always obtain a unique order of inheritance. Implement the `ThroneInheritance` class: * `ThroneInheritance(string kingName)` Initializes an object of the `ThroneInheritance` class. The name of the king is given as part of the constructor. * `void birth(string parentName, string childName)` Indicates that `parentName` gave birth to `childName`. * `void death(string name)` Indicates the death of `name`. The death of the person doesn't affect the `Successor` function nor the current inheritance order. You can treat it as just marking the person as dead. * `string[] getInheritanceOrder()` Returns a list representing the current order of inheritance **excluding** dead people. **Example 1:** **Input** \[ "ThroneInheritance ", "birth ", "birth ", "birth ", "birth ", "birth ", "birth ", "getInheritanceOrder ", "death ", "getInheritanceOrder "\] \[\[ "king "\], \[ "king ", "andy "\], \[ "king ", "bob "\], \[ "king ", "catherine "\], \[ "andy ", "matthew "\], \[ "bob ", "alex "\], \[ "bob ", "asha "\], \[null\], \[ "bob "\], \[null\]\] **Output** \[null, null, null, null, null, null, null, \[ "king ", "andy ", "matthew ", "bob ", "alex ", "asha ", "catherine "\], null, \[ "king ", "andy ", "matthew ", "alex ", "asha ", "catherine "\]\] **Explanation** ThroneInheritance t= new ThroneInheritance( "king "); // order: **king** t.birth( "king ", "andy "); // order: king > **andy** t.birth( "king ", "bob "); // order: king > andy > **bob** t.birth( "king ", "catherine "); // order: king > andy > bob > **catherine** t.birth( "andy ", "matthew "); // order: king > andy > **matthew** > bob > catherine t.birth( "bob ", "alex "); // order: king > andy > matthew > bob > **alex** > catherine t.birth( "bob ", "asha "); // order: king > andy > matthew > bob > alex > **asha** > catherine t.getInheritanceOrder(); // return \[ "king ", "andy ", "matthew ", "bob ", "alex ", "asha ", "catherine "\] t.death( "bob "); // order: king > andy > matthew > **bob** > alex > asha > catherine t.getInheritanceOrder(); // return \[ "king ", "andy ", "matthew ", "alex ", "asha ", "catherine "\] **Constraints:** * `1 <= kingName.length, parentName.length, childName.length, name.length <= 15` * `kingName`, `parentName`, `childName`, and `name` consist of lowercase English letters only. * All arguments `childName` and `kingName` are **distinct**. * All `name` arguments of `death` will be passed to either the constructor or as `childName` to `birth` first. * For each call to `birth(parentName, childName)`, it is guaranteed that `parentName` is alive. * At most `105` calls will be made to `birth` and `death`. * At most `10` calls will be made to `getInheritanceOrder`.
null
BEATS 95.00%! | Python3 Fast Easy Solution Explained
throne-inheritance
0
1
The explanation\'s in the code comments.\n# Code\n```\nclass ThroneInheritance:\n def __init__(self, kingName: str):\n # This is equivalent to the root node in a tree.\n self.kingName = kingName\n # Since we know that all family members\' names are distinct,\n # (no two names are the same), we can use a hash table.\n # Anyone who has descendants is a "key" in this hash table.\n self.ht = {kingName: []}\n # Keep track of who dies.\n self.deaths = set()\n\n def birth(self, parentName: str, childName: str) -> None:\n # Updates the family tree.\n if parentName not in self.ht:\n self.ht[parentName] = []\n self.ht[parentName].append(childName)\n\n def death(self, name: str) -> None:\n # Updates who dies.\n self.deaths.add(name)\n\n def getInheritanceOrder(self) -> List[str]:\n inheritanceOrder = []\n stack = [self.kingName]\n name = ""\n # Traverses the family tree.\n while len(stack) > 0:\n # Get the current name.\n name = stack.pop()\n # Add the person to the inheritance order if\n # he or she is still alive.\n if name not in self.deaths:\n inheritanceOrder.append(name)\n # Add the person\'s descendants to the stack in\n # reverse order if they exist.\n if name in self.ht:\n for i in range(len(self.ht[name])-1, -1, -1):\n stack.append(self.ht[name][i])\n return inheritanceOrder\n\n```
0
You are given two integer arrays, `source` and `target`, both of length `n`. You are also given an array `allowedSwaps` where each `allowedSwaps[i] = [ai, bi]` indicates that you are allowed to swap the elements at index `ai` and index `bi` **(0-indexed)** of array `source`. Note that you can swap elements at a specific pair of indices **multiple** times and in **any** order. The **Hamming distance** of two arrays of the same length, `source` and `target`, is the number of positions where the elements are different. Formally, it is the number of indices `i` for `0 <= i <= n-1` where `source[i] != target[i]` **(0-indexed)**. Return _the **minimum Hamming distance** of_ `source` _and_ `target` _after performing **any** amount of swap operations on array_ `source`_._ **Example 1:** **Input:** source = \[1,2,3,4\], target = \[2,1,4,5\], allowedSwaps = \[\[0,1\],\[2,3\]\] **Output:** 1 **Explanation:** source can be transformed the following way: - Swap indices 0 and 1: source = \[2,1,3,4\] - Swap indices 2 and 3: source = \[2,1,4,3\] The Hamming distance of source and target is 1 as they differ in 1 position: index 3. **Example 2:** **Input:** source = \[1,2,3,4\], target = \[1,3,2,4\], allowedSwaps = \[\] **Output:** 2 **Explanation:** There are no allowed swaps. The Hamming distance of source and target is 2 as they differ in 2 positions: index 1 and index 2. **Example 3:** **Input:** source = \[5,1,2,4,3\], target = \[1,5,4,2,3\], allowedSwaps = \[\[0,4\],\[4,2\],\[1,3\],\[1,4\]\] **Output:** 0 **Constraints:** * `n == source.length == target.length` * `1 <= n <= 105` * `1 <= source[i], target[i] <= 105` * `0 <= allowedSwaps.length <= 105` * `allowedSwaps[i].length == 2` * `0 <= ai, bi <= n - 1` * `ai != bi`
Create a tree structure of the family. Without deaths, the order of inheritance is simply a pre-order traversal of the tree. Mark the dead family members tree nodes and don't include them in the final order.
Python - N-tree
throne-inheritance
0
1
# Intuition\nJust construct n-tree and maintain set of dead people.\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(n)$$ - getInheritanceOrder\n$$O(1)$$ - birth\n$$O(1)$$ - death\n\n# Code\n```\nclass ThroneInheritance:\n\n def __init__(self, kingName: str):\n self.succ = defaultdict(list)\n self.king = kingName\n self.dead = set()\n \n def birth(self, parentName: str, childName: str) -> None:\n self.succ[parentName].append(childName)\n\n def death(self, name: str) -> None:\n self.dead.add(name)\n\n def collect(self, name, order):\n if name not in self.dead: order.append(name)\n for child in self.succ[name]: self.collect(child, order)\n\n def getInheritanceOrder(self) -> List[str]:\n result = []\n self.collect(self.king, result)\n return result \n```
0
A kingdom consists of a king, his children, his grandchildren, and so on. Every once in a while, someone in the family dies or a child is born. The kingdom has a well-defined order of inheritance that consists of the king as the first member. Let's define the recursive function `Successor(x, curOrder)`, which given a person `x` and the inheritance order so far, returns who should be the next person after `x` in the order of inheritance. Successor(x, curOrder): if x has no children or all of x's children are in curOrder: if x is the king return null else return Successor(x's parent, curOrder) else return x's oldest child who's not in curOrder For example, assume we have a kingdom that consists of the king, his children Alice and Bob (Alice is older than Bob), and finally Alice's son Jack. 1. In the beginning, `curOrder` will be `[ "king "]`. 2. Calling `Successor(king, curOrder)` will return Alice, so we append to `curOrder` to get `[ "king ", "Alice "]`. 3. Calling `Successor(Alice, curOrder)` will return Jack, so we append to `curOrder` to get `[ "king ", "Alice ", "Jack "]`. 4. Calling `Successor(Jack, curOrder)` will return Bob, so we append to `curOrder` to get `[ "king ", "Alice ", "Jack ", "Bob "]`. 5. Calling `Successor(Bob, curOrder)` will return `null`. Thus the order of inheritance will be `[ "king ", "Alice ", "Jack ", "Bob "]`. Using the above function, we can always obtain a unique order of inheritance. Implement the `ThroneInheritance` class: * `ThroneInheritance(string kingName)` Initializes an object of the `ThroneInheritance` class. The name of the king is given as part of the constructor. * `void birth(string parentName, string childName)` Indicates that `parentName` gave birth to `childName`. * `void death(string name)` Indicates the death of `name`. The death of the person doesn't affect the `Successor` function nor the current inheritance order. You can treat it as just marking the person as dead. * `string[] getInheritanceOrder()` Returns a list representing the current order of inheritance **excluding** dead people. **Example 1:** **Input** \[ "ThroneInheritance ", "birth ", "birth ", "birth ", "birth ", "birth ", "birth ", "getInheritanceOrder ", "death ", "getInheritanceOrder "\] \[\[ "king "\], \[ "king ", "andy "\], \[ "king ", "bob "\], \[ "king ", "catherine "\], \[ "andy ", "matthew "\], \[ "bob ", "alex "\], \[ "bob ", "asha "\], \[null\], \[ "bob "\], \[null\]\] **Output** \[null, null, null, null, null, null, null, \[ "king ", "andy ", "matthew ", "bob ", "alex ", "asha ", "catherine "\], null, \[ "king ", "andy ", "matthew ", "alex ", "asha ", "catherine "\]\] **Explanation** ThroneInheritance t= new ThroneInheritance( "king "); // order: **king** t.birth( "king ", "andy "); // order: king > **andy** t.birth( "king ", "bob "); // order: king > andy > **bob** t.birth( "king ", "catherine "); // order: king > andy > bob > **catherine** t.birth( "andy ", "matthew "); // order: king > andy > **matthew** > bob > catherine t.birth( "bob ", "alex "); // order: king > andy > matthew > bob > **alex** > catherine t.birth( "bob ", "asha "); // order: king > andy > matthew > bob > alex > **asha** > catherine t.getInheritanceOrder(); // return \[ "king ", "andy ", "matthew ", "bob ", "alex ", "asha ", "catherine "\] t.death( "bob "); // order: king > andy > matthew > **bob** > alex > asha > catherine t.getInheritanceOrder(); // return \[ "king ", "andy ", "matthew ", "alex ", "asha ", "catherine "\] **Constraints:** * `1 <= kingName.length, parentName.length, childName.length, name.length <= 15` * `kingName`, `parentName`, `childName`, and `name` consist of lowercase English letters only. * All arguments `childName` and `kingName` are **distinct**. * All `name` arguments of `death` will be passed to either the constructor or as `childName` to `birth` first. * For each call to `birth(parentName, childName)`, it is guaranteed that `parentName` is alive. * At most `105` calls will be made to `birth` and `death`. * At most `10` calls will be made to `getInheritanceOrder`.
null
Python - N-tree
throne-inheritance
0
1
# Intuition\nJust construct n-tree and maintain set of dead people.\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(n)$$ - getInheritanceOrder\n$$O(1)$$ - birth\n$$O(1)$$ - death\n\n# Code\n```\nclass ThroneInheritance:\n\n def __init__(self, kingName: str):\n self.succ = defaultdict(list)\n self.king = kingName\n self.dead = set()\n \n def birth(self, parentName: str, childName: str) -> None:\n self.succ[parentName].append(childName)\n\n def death(self, name: str) -> None:\n self.dead.add(name)\n\n def collect(self, name, order):\n if name not in self.dead: order.append(name)\n for child in self.succ[name]: self.collect(child, order)\n\n def getInheritanceOrder(self) -> List[str]:\n result = []\n self.collect(self.king, result)\n return result \n```
0
You are given two integer arrays, `source` and `target`, both of length `n`. You are also given an array `allowedSwaps` where each `allowedSwaps[i] = [ai, bi]` indicates that you are allowed to swap the elements at index `ai` and index `bi` **(0-indexed)** of array `source`. Note that you can swap elements at a specific pair of indices **multiple** times and in **any** order. The **Hamming distance** of two arrays of the same length, `source` and `target`, is the number of positions where the elements are different. Formally, it is the number of indices `i` for `0 <= i <= n-1` where `source[i] != target[i]` **(0-indexed)**. Return _the **minimum Hamming distance** of_ `source` _and_ `target` _after performing **any** amount of swap operations on array_ `source`_._ **Example 1:** **Input:** source = \[1,2,3,4\], target = \[2,1,4,5\], allowedSwaps = \[\[0,1\],\[2,3\]\] **Output:** 1 **Explanation:** source can be transformed the following way: - Swap indices 0 and 1: source = \[2,1,3,4\] - Swap indices 2 and 3: source = \[2,1,4,3\] The Hamming distance of source and target is 1 as they differ in 1 position: index 3. **Example 2:** **Input:** source = \[1,2,3,4\], target = \[1,3,2,4\], allowedSwaps = \[\] **Output:** 2 **Explanation:** There are no allowed swaps. The Hamming distance of source and target is 2 as they differ in 2 positions: index 1 and index 2. **Example 3:** **Input:** source = \[5,1,2,4,3\], target = \[1,5,4,2,3\], allowedSwaps = \[\[0,4\],\[4,2\],\[1,3\],\[1,4\]\] **Output:** 0 **Constraints:** * `n == source.length == target.length` * `1 <= n <= 105` * `1 <= source[i], target[i] <= 105` * `0 <= allowedSwaps.length <= 105` * `allowedSwaps[i].length == 2` * `0 <= ai, bi <= n - 1` * `ai != bi`
Create a tree structure of the family. Without deaths, the order of inheritance is simply a pre-order traversal of the tree. Mark the dead family members tree nodes and don't include them in the final order.
Simple Python3 DFS
throne-inheritance
0
1
\n\n# Code\n```\nclass ThroneInheritance:\n\n def __init__(self, kingName: str):\n self.family = defaultdict(list)\n self.king = kingName\n self.dead = defaultdict(bool)\n \n def birth(self, parentName: str, childName: str) -> None:\n self.family[parentName].append(childName)\n\n def death(self, name: str) -> None:\n self.dead[name] = True\n\n def getInheritanceOrder(self) -> List[str]:\n visited = set()\n curOrder = [self.king] if not self.dead[self.king] else []\n\n def successor(parent, curOrder):\n if parent not in visited:\n visited.add(parent)\n for child in self.family[parent]:\n if not self.dead[child]:\n curOrder.append(child)\n successor(child,curOrder)\n return curOrder\n \n return successor(self.king, curOrder)\n\n\n\n\n \n\n\n# Your ThroneInheritance object will be instantiated and called as such:\n# obj = ThroneInheritance(kingName)\n# obj.birth(parentName,childName)\n# obj.death(name)\n# param_3 = obj.getInheritanceOrder()\n```
0
A kingdom consists of a king, his children, his grandchildren, and so on. Every once in a while, someone in the family dies or a child is born. The kingdom has a well-defined order of inheritance that consists of the king as the first member. Let's define the recursive function `Successor(x, curOrder)`, which given a person `x` and the inheritance order so far, returns who should be the next person after `x` in the order of inheritance. Successor(x, curOrder): if x has no children or all of x's children are in curOrder: if x is the king return null else return Successor(x's parent, curOrder) else return x's oldest child who's not in curOrder For example, assume we have a kingdom that consists of the king, his children Alice and Bob (Alice is older than Bob), and finally Alice's son Jack. 1. In the beginning, `curOrder` will be `[ "king "]`. 2. Calling `Successor(king, curOrder)` will return Alice, so we append to `curOrder` to get `[ "king ", "Alice "]`. 3. Calling `Successor(Alice, curOrder)` will return Jack, so we append to `curOrder` to get `[ "king ", "Alice ", "Jack "]`. 4. Calling `Successor(Jack, curOrder)` will return Bob, so we append to `curOrder` to get `[ "king ", "Alice ", "Jack ", "Bob "]`. 5. Calling `Successor(Bob, curOrder)` will return `null`. Thus the order of inheritance will be `[ "king ", "Alice ", "Jack ", "Bob "]`. Using the above function, we can always obtain a unique order of inheritance. Implement the `ThroneInheritance` class: * `ThroneInheritance(string kingName)` Initializes an object of the `ThroneInheritance` class. The name of the king is given as part of the constructor. * `void birth(string parentName, string childName)` Indicates that `parentName` gave birth to `childName`. * `void death(string name)` Indicates the death of `name`. The death of the person doesn't affect the `Successor` function nor the current inheritance order. You can treat it as just marking the person as dead. * `string[] getInheritanceOrder()` Returns a list representing the current order of inheritance **excluding** dead people. **Example 1:** **Input** \[ "ThroneInheritance ", "birth ", "birth ", "birth ", "birth ", "birth ", "birth ", "getInheritanceOrder ", "death ", "getInheritanceOrder "\] \[\[ "king "\], \[ "king ", "andy "\], \[ "king ", "bob "\], \[ "king ", "catherine "\], \[ "andy ", "matthew "\], \[ "bob ", "alex "\], \[ "bob ", "asha "\], \[null\], \[ "bob "\], \[null\]\] **Output** \[null, null, null, null, null, null, null, \[ "king ", "andy ", "matthew ", "bob ", "alex ", "asha ", "catherine "\], null, \[ "king ", "andy ", "matthew ", "alex ", "asha ", "catherine "\]\] **Explanation** ThroneInheritance t= new ThroneInheritance( "king "); // order: **king** t.birth( "king ", "andy "); // order: king > **andy** t.birth( "king ", "bob "); // order: king > andy > **bob** t.birth( "king ", "catherine "); // order: king > andy > bob > **catherine** t.birth( "andy ", "matthew "); // order: king > andy > **matthew** > bob > catherine t.birth( "bob ", "alex "); // order: king > andy > matthew > bob > **alex** > catherine t.birth( "bob ", "asha "); // order: king > andy > matthew > bob > alex > **asha** > catherine t.getInheritanceOrder(); // return \[ "king ", "andy ", "matthew ", "bob ", "alex ", "asha ", "catherine "\] t.death( "bob "); // order: king > andy > matthew > **bob** > alex > asha > catherine t.getInheritanceOrder(); // return \[ "king ", "andy ", "matthew ", "alex ", "asha ", "catherine "\] **Constraints:** * `1 <= kingName.length, parentName.length, childName.length, name.length <= 15` * `kingName`, `parentName`, `childName`, and `name` consist of lowercase English letters only. * All arguments `childName` and `kingName` are **distinct**. * All `name` arguments of `death` will be passed to either the constructor or as `childName` to `birth` first. * For each call to `birth(parentName, childName)`, it is guaranteed that `parentName` is alive. * At most `105` calls will be made to `birth` and `death`. * At most `10` calls will be made to `getInheritanceOrder`.
null
Simple Python3 DFS
throne-inheritance
0
1
\n\n# Code\n```\nclass ThroneInheritance:\n\n def __init__(self, kingName: str):\n self.family = defaultdict(list)\n self.king = kingName\n self.dead = defaultdict(bool)\n \n def birth(self, parentName: str, childName: str) -> None:\n self.family[parentName].append(childName)\n\n def death(self, name: str) -> None:\n self.dead[name] = True\n\n def getInheritanceOrder(self) -> List[str]:\n visited = set()\n curOrder = [self.king] if not self.dead[self.king] else []\n\n def successor(parent, curOrder):\n if parent not in visited:\n visited.add(parent)\n for child in self.family[parent]:\n if not self.dead[child]:\n curOrder.append(child)\n successor(child,curOrder)\n return curOrder\n \n return successor(self.king, curOrder)\n\n\n\n\n \n\n\n# Your ThroneInheritance object will be instantiated and called as such:\n# obj = ThroneInheritance(kingName)\n# obj.birth(parentName,childName)\n# obj.death(name)\n# param_3 = obj.getInheritanceOrder()\n```
0
You are given two integer arrays, `source` and `target`, both of length `n`. You are also given an array `allowedSwaps` where each `allowedSwaps[i] = [ai, bi]` indicates that you are allowed to swap the elements at index `ai` and index `bi` **(0-indexed)** of array `source`. Note that you can swap elements at a specific pair of indices **multiple** times and in **any** order. The **Hamming distance** of two arrays of the same length, `source` and `target`, is the number of positions where the elements are different. Formally, it is the number of indices `i` for `0 <= i <= n-1` where `source[i] != target[i]` **(0-indexed)**. Return _the **minimum Hamming distance** of_ `source` _and_ `target` _after performing **any** amount of swap operations on array_ `source`_._ **Example 1:** **Input:** source = \[1,2,3,4\], target = \[2,1,4,5\], allowedSwaps = \[\[0,1\],\[2,3\]\] **Output:** 1 **Explanation:** source can be transformed the following way: - Swap indices 0 and 1: source = \[2,1,3,4\] - Swap indices 2 and 3: source = \[2,1,4,3\] The Hamming distance of source and target is 1 as they differ in 1 position: index 3. **Example 2:** **Input:** source = \[1,2,3,4\], target = \[1,3,2,4\], allowedSwaps = \[\] **Output:** 2 **Explanation:** There are no allowed swaps. The Hamming distance of source and target is 2 as they differ in 2 positions: index 1 and index 2. **Example 3:** **Input:** source = \[5,1,2,4,3\], target = \[1,5,4,2,3\], allowedSwaps = \[\[0,4\],\[4,2\],\[1,3\],\[1,4\]\] **Output:** 0 **Constraints:** * `n == source.length == target.length` * `1 <= n <= 105` * `1 <= source[i], target[i] <= 105` * `0 <= allowedSwaps.length <= 105` * `allowedSwaps[i].length == 2` * `0 <= ai, bi <= n - 1` * `ai != bi`
Create a tree structure of the family. Without deaths, the order of inheritance is simply a pre-order traversal of the tree. Mark the dead family members tree nodes and don't include them in the final order.
Simple DFS | Beats 98%
throne-inheritance
0
1
```\nclass ThroneInheritance:\n\n def __init__(self, kingName: str):\n self.king = kingName\n self.map = {kingName: []}\n self.dead = set()\n\n def birth(self, parentName: str, childName: str) -> None:\n if parentName in self.map:\n self.map[parentName].append(childName)\n else:\n self.map[parentName] = [childName]\n\n def death(self, name: str) -> None:\n self.dead.add(name)\n\n def getInheritanceOrder(self) -> List[str]:\n order = []\n def dfs(person=self.king):\n if person not in self.dead:\n order.append(person)\n\n if person in self.map:\n for child in self.map[person]:\n dfs(child)\n dfs()\n return order\n```
0
A kingdom consists of a king, his children, his grandchildren, and so on. Every once in a while, someone in the family dies or a child is born. The kingdom has a well-defined order of inheritance that consists of the king as the first member. Let's define the recursive function `Successor(x, curOrder)`, which given a person `x` and the inheritance order so far, returns who should be the next person after `x` in the order of inheritance. Successor(x, curOrder): if x has no children or all of x's children are in curOrder: if x is the king return null else return Successor(x's parent, curOrder) else return x's oldest child who's not in curOrder For example, assume we have a kingdom that consists of the king, his children Alice and Bob (Alice is older than Bob), and finally Alice's son Jack. 1. In the beginning, `curOrder` will be `[ "king "]`. 2. Calling `Successor(king, curOrder)` will return Alice, so we append to `curOrder` to get `[ "king ", "Alice "]`. 3. Calling `Successor(Alice, curOrder)` will return Jack, so we append to `curOrder` to get `[ "king ", "Alice ", "Jack "]`. 4. Calling `Successor(Jack, curOrder)` will return Bob, so we append to `curOrder` to get `[ "king ", "Alice ", "Jack ", "Bob "]`. 5. Calling `Successor(Bob, curOrder)` will return `null`. Thus the order of inheritance will be `[ "king ", "Alice ", "Jack ", "Bob "]`. Using the above function, we can always obtain a unique order of inheritance. Implement the `ThroneInheritance` class: * `ThroneInheritance(string kingName)` Initializes an object of the `ThroneInheritance` class. The name of the king is given as part of the constructor. * `void birth(string parentName, string childName)` Indicates that `parentName` gave birth to `childName`. * `void death(string name)` Indicates the death of `name`. The death of the person doesn't affect the `Successor` function nor the current inheritance order. You can treat it as just marking the person as dead. * `string[] getInheritanceOrder()` Returns a list representing the current order of inheritance **excluding** dead people. **Example 1:** **Input** \[ "ThroneInheritance ", "birth ", "birth ", "birth ", "birth ", "birth ", "birth ", "getInheritanceOrder ", "death ", "getInheritanceOrder "\] \[\[ "king "\], \[ "king ", "andy "\], \[ "king ", "bob "\], \[ "king ", "catherine "\], \[ "andy ", "matthew "\], \[ "bob ", "alex "\], \[ "bob ", "asha "\], \[null\], \[ "bob "\], \[null\]\] **Output** \[null, null, null, null, null, null, null, \[ "king ", "andy ", "matthew ", "bob ", "alex ", "asha ", "catherine "\], null, \[ "king ", "andy ", "matthew ", "alex ", "asha ", "catherine "\]\] **Explanation** ThroneInheritance t= new ThroneInheritance( "king "); // order: **king** t.birth( "king ", "andy "); // order: king > **andy** t.birth( "king ", "bob "); // order: king > andy > **bob** t.birth( "king ", "catherine "); // order: king > andy > bob > **catherine** t.birth( "andy ", "matthew "); // order: king > andy > **matthew** > bob > catherine t.birth( "bob ", "alex "); // order: king > andy > matthew > bob > **alex** > catherine t.birth( "bob ", "asha "); // order: king > andy > matthew > bob > alex > **asha** > catherine t.getInheritanceOrder(); // return \[ "king ", "andy ", "matthew ", "bob ", "alex ", "asha ", "catherine "\] t.death( "bob "); // order: king > andy > matthew > **bob** > alex > asha > catherine t.getInheritanceOrder(); // return \[ "king ", "andy ", "matthew ", "alex ", "asha ", "catherine "\] **Constraints:** * `1 <= kingName.length, parentName.length, childName.length, name.length <= 15` * `kingName`, `parentName`, `childName`, and `name` consist of lowercase English letters only. * All arguments `childName` and `kingName` are **distinct**. * All `name` arguments of `death` will be passed to either the constructor or as `childName` to `birth` first. * For each call to `birth(parentName, childName)`, it is guaranteed that `parentName` is alive. * At most `105` calls will be made to `birth` and `death`. * At most `10` calls will be made to `getInheritanceOrder`.
null
Simple DFS | Beats 98%
throne-inheritance
0
1
```\nclass ThroneInheritance:\n\n def __init__(self, kingName: str):\n self.king = kingName\n self.map = {kingName: []}\n self.dead = set()\n\n def birth(self, parentName: str, childName: str) -> None:\n if parentName in self.map:\n self.map[parentName].append(childName)\n else:\n self.map[parentName] = [childName]\n\n def death(self, name: str) -> None:\n self.dead.add(name)\n\n def getInheritanceOrder(self) -> List[str]:\n order = []\n def dfs(person=self.king):\n if person not in self.dead:\n order.append(person)\n\n if person in self.map:\n for child in self.map[person]:\n dfs(child)\n dfs()\n return order\n```
0
You are given two integer arrays, `source` and `target`, both of length `n`. You are also given an array `allowedSwaps` where each `allowedSwaps[i] = [ai, bi]` indicates that you are allowed to swap the elements at index `ai` and index `bi` **(0-indexed)** of array `source`. Note that you can swap elements at a specific pair of indices **multiple** times and in **any** order. The **Hamming distance** of two arrays of the same length, `source` and `target`, is the number of positions where the elements are different. Formally, it is the number of indices `i` for `0 <= i <= n-1` where `source[i] != target[i]` **(0-indexed)**. Return _the **minimum Hamming distance** of_ `source` _and_ `target` _after performing **any** amount of swap operations on array_ `source`_._ **Example 1:** **Input:** source = \[1,2,3,4\], target = \[2,1,4,5\], allowedSwaps = \[\[0,1\],\[2,3\]\] **Output:** 1 **Explanation:** source can be transformed the following way: - Swap indices 0 and 1: source = \[2,1,3,4\] - Swap indices 2 and 3: source = \[2,1,4,3\] The Hamming distance of source and target is 1 as they differ in 1 position: index 3. **Example 2:** **Input:** source = \[1,2,3,4\], target = \[1,3,2,4\], allowedSwaps = \[\] **Output:** 2 **Explanation:** There are no allowed swaps. The Hamming distance of source and target is 2 as they differ in 2 positions: index 1 and index 2. **Example 3:** **Input:** source = \[5,1,2,4,3\], target = \[1,5,4,2,3\], allowedSwaps = \[\[0,4\],\[4,2\],\[1,3\],\[1,4\]\] **Output:** 0 **Constraints:** * `n == source.length == target.length` * `1 <= n <= 105` * `1 <= source[i], target[i] <= 105` * `0 <= allowedSwaps.length <= 105` * `allowedSwaps[i].length == 2` * `0 <= ai, bi <= n - 1` * `ai != bi`
Create a tree structure of the family. Without deaths, the order of inheritance is simply a pre-order traversal of the tree. Mark the dead family members tree nodes and don't include them in the final order.
Backtracking | C++ | Python | Golang
maximum-number-of-achievable-transfer-requests
0
1
# Code\n```C++ []\nclass Solution {\npublic:\n int maximumRequests(int n, vector<vector<int>>& requests) {\n int answer = 0;\n vector<int> indegree(n, 0);\n\n function<void(int, int)> maxRequest = [&](int index, int count) {\n if (index == requests.size()) {\n for (int i = 0; i < n; i++) {\n if (indegree[i]) {\n return;\n }\n }\n answer = max(answer, count);\n return;\n }\n\n indegree[requests[index][0]]--;\n indegree[requests[index][1]]++;\n\n maxRequest(index + 1, count + 1);\n\n indegree[requests[index][0]]++;\n indegree[requests[index][1]]--;\n\n maxRequest(index + 1, count);\n };\n\n maxRequest(0, 0);\n\n return answer;\n }\n};\n```\n```Python []\nclass Solution:\n def maximumRequests(self, n: int, requests: List[List[int]]) -> int:\n answer = 0\n indegree = [0 for _ in range(n)]\n\n def maxRequest(index, count):\n if(index == len(requests)):\n for i in range(n):\n if(indegree[i]):\n return\n nonlocal answer\n answer = max(answer, count)\n return\n\n indegree[requests[index][0]] -= 1\n indegree[requests[index][1]] += 1\n\n maxRequest(index + 1, count + 1)\n\n indegree[requests[index][0]] += 1\n indegree[requests[index][1]] -= 1\n\n maxRequest(index + 1, count)\n\n maxRequest(0, 0)\n\n return answer\n```\n```Go []\nfunc maximumRequests(n int, requests [][]int) int {\n answer := 0\n indegree := make([]int, n)\n\n var maxRequest func(int, int)\n\n maxRequest = func (index, count int) {\n if(index == len(requests)) {\n for i := 0; i < n; i++ {\n if(indegree[i] != 0) {\n return;\n }\n }\n\n if(count > answer) {\n answer = count\n }\n return\n }\n\n indegree[requests[index][0]] --;\n indegree[requests[index][1]] ++;\n\n maxRequest(index + 1, count + 1)\n\n indegree[requests[index][0]] ++;\n indegree[requests[index][1]] --;\n\n maxRequest(index + 1, count)\n }\n\n maxRequest(0, 0)\n\n return answer\n}\n```
3
We have `n` buildings numbered from `0` to `n - 1`. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in. You are given an array `requests` where `requests[i] = [fromi, toi]` represents an employee's request to transfer from building `fromi` to building `toi`. **All buildings are full**, so a list of requests is achievable only if for each building, the **net change in employee transfers is zero**. This means the number of employees **leaving** is **equal** to the number of employees **moving in**. For example if `n = 3` and two employees are leaving building `0`, one is leaving building `1`, and one is leaving building `2`, there should be two employees moving to building `0`, one employee moving to building `1`, and one employee moving to building `2`. Return _the maximum number of achievable requests_. **Example 1:** **Input:** n = 5, requests = \[\[0,1\],\[1,0\],\[0,1\],\[1,2\],\[2,0\],\[3,4\]\] **Output:** 5 **Explantion:** Let's see the requests: From building 0 we have employees x and y and both want to move to building 1. From building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively. From building 2 we have employee z and they want to move to building 0. From building 3 we have employee c and they want to move to building 4. From building 4 we don't have any requests. We can achieve the requests of users x and b by swapping their places. We can achieve the requests of users y, a and z by swapping the places in the 3 buildings. **Example 2:** **Input:** n = 3, requests = \[\[0,0\],\[1,2\],\[2,1\]\] **Output:** 3 **Explantion:** Let's see the requests: From building 0 we have employee x and they want to stay in the same building 0. From building 1 we have employee y and they want to move to building 2. From building 2 we have employee z and they want to move to building 1. We can achieve all the requests. **Example 3:** **Input:** n = 4, requests = \[\[0,3\],\[3,1\],\[1,2\],\[2,0\]\] **Output:** 4 **Constraints:** * `1 <= n <= 20` * `1 <= requests.length <= 16` * `requests[i].length == 2` * `0 <= fromi, toi < n`
null
Backtracking | C++ | Python | Golang
maximum-number-of-achievable-transfer-requests
0
1
# Code\n```C++ []\nclass Solution {\npublic:\n int maximumRequests(int n, vector<vector<int>>& requests) {\n int answer = 0;\n vector<int> indegree(n, 0);\n\n function<void(int, int)> maxRequest = [&](int index, int count) {\n if (index == requests.size()) {\n for (int i = 0; i < n; i++) {\n if (indegree[i]) {\n return;\n }\n }\n answer = max(answer, count);\n return;\n }\n\n indegree[requests[index][0]]--;\n indegree[requests[index][1]]++;\n\n maxRequest(index + 1, count + 1);\n\n indegree[requests[index][0]]++;\n indegree[requests[index][1]]--;\n\n maxRequest(index + 1, count);\n };\n\n maxRequest(0, 0);\n\n return answer;\n }\n};\n```\n```Python []\nclass Solution:\n def maximumRequests(self, n: int, requests: List[List[int]]) -> int:\n answer = 0\n indegree = [0 for _ in range(n)]\n\n def maxRequest(index, count):\n if(index == len(requests)):\n for i in range(n):\n if(indegree[i]):\n return\n nonlocal answer\n answer = max(answer, count)\n return\n\n indegree[requests[index][0]] -= 1\n indegree[requests[index][1]] += 1\n\n maxRequest(index + 1, count + 1)\n\n indegree[requests[index][0]] += 1\n indegree[requests[index][1]] -= 1\n\n maxRequest(index + 1, count)\n\n maxRequest(0, 0)\n\n return answer\n```\n```Go []\nfunc maximumRequests(n int, requests [][]int) int {\n answer := 0\n indegree := make([]int, n)\n\n var maxRequest func(int, int)\n\n maxRequest = func (index, count int) {\n if(index == len(requests)) {\n for i := 0; i < n; i++ {\n if(indegree[i] != 0) {\n return;\n }\n }\n\n if(count > answer) {\n answer = count\n }\n return\n }\n\n indegree[requests[index][0]] --;\n indegree[requests[index][1]] ++;\n\n maxRequest(index + 1, count + 1)\n\n indegree[requests[index][0]] ++;\n indegree[requests[index][1]] --;\n\n maxRequest(index + 1, count)\n }\n\n maxRequest(0, 0)\n\n return answer\n}\n```
3
You are given an integer array `jobs`, where `jobs[i]` is the amount of time it takes to complete the `ith` job. There are `k` workers that you can assign jobs to. Each job should be assigned to **exactly** one worker. The **working time** of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the **maximum working time** of any worker is **minimized**. _Return the **minimum** possible **maximum working time** of any assignment._ **Example 1:** **Input:** jobs = \[3,2,3\], k = 3 **Output:** 3 **Explanation:** By assigning each person one job, the maximum time is 3. **Example 2:** **Input:** jobs = \[1,2,4,7,8\], k = 2 **Output:** 11 **Explanation:** Assign the jobs the following way: Worker 1: 1, 2, 8 (working time = 1 + 2 + 8 = 11) Worker 2: 4, 7 (working time = 4 + 7 = 11) The maximum working time is 11. **Constraints:** * `1 <= k <= jobs.length <= 12` * `1 <= jobs[i] <= 107`
Think brute force When is a subset of requests okay?
Python 3 || 5 lines, combinations, w/ explanation || T/M: 91% / 98%
maximum-number-of-achievable-transfer-requests
0
1
Here\'s how the code works:\n\n1. We use a brute-force approach to find the maximum number of achievable requests (`cnt`). It starts by considering the maximum possible number of requests (`len(requests)`), and decrementing `cnt` until either a solution is found or we exhaust all possibilities.\n\n1. We iterate in reverse order over the range from 1 to `len(requests)`. For each iteration, we consider all combinations of requests with the given count. \n\n1. For each combination, we unzip combinations to lists of`to`and`frm`. If`to`and`frm` have the same elements for some combination (which we check with `sorted(to) == sorted(frm)`) then we return`cnt`as the solution. If no such combination exists, we return 0.\n```\nclass Solution:\n def maximumRequests(self, n: int, requests: List[List[int]]) -> int:\n\n for cnt in reversed(range(1, len(requests)+1)):\n \n for com in combinations(requests,cnt):\n to, frm = map(sorted,zip(*com))\n if sorted(to) == sorted(frm): return cnt\n\n return 0\n```\n[https://leetcode.com/problems/maximum-number-of-achievable-transfer-requests/submissions/988756024/](http://)\n\nPython 3 || 5 lines, combinations, w/ explanation || T/M: 91% / 98%\n\nI could be wrong, but I think that time complexity (worst case) is *O*(2^*M* * *MN*log*N*) and space complexity is *O*(*M*), in which *M* ~ `len(requests)` and *N* ~ `n`.
3
We have `n` buildings numbered from `0` to `n - 1`. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in. You are given an array `requests` where `requests[i] = [fromi, toi]` represents an employee's request to transfer from building `fromi` to building `toi`. **All buildings are full**, so a list of requests is achievable only if for each building, the **net change in employee transfers is zero**. This means the number of employees **leaving** is **equal** to the number of employees **moving in**. For example if `n = 3` and two employees are leaving building `0`, one is leaving building `1`, and one is leaving building `2`, there should be two employees moving to building `0`, one employee moving to building `1`, and one employee moving to building `2`. Return _the maximum number of achievable requests_. **Example 1:** **Input:** n = 5, requests = \[\[0,1\],\[1,0\],\[0,1\],\[1,2\],\[2,0\],\[3,4\]\] **Output:** 5 **Explantion:** Let's see the requests: From building 0 we have employees x and y and both want to move to building 1. From building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively. From building 2 we have employee z and they want to move to building 0. From building 3 we have employee c and they want to move to building 4. From building 4 we don't have any requests. We can achieve the requests of users x and b by swapping their places. We can achieve the requests of users y, a and z by swapping the places in the 3 buildings. **Example 2:** **Input:** n = 3, requests = \[\[0,0\],\[1,2\],\[2,1\]\] **Output:** 3 **Explantion:** Let's see the requests: From building 0 we have employee x and they want to stay in the same building 0. From building 1 we have employee y and they want to move to building 2. From building 2 we have employee z and they want to move to building 1. We can achieve all the requests. **Example 3:** **Input:** n = 4, requests = \[\[0,3\],\[3,1\],\[1,2\],\[2,0\]\] **Output:** 4 **Constraints:** * `1 <= n <= 20` * `1 <= requests.length <= 16` * `requests[i].length == 2` * `0 <= fromi, toi < n`
null
Python 3 || 5 lines, combinations, w/ explanation || T/M: 91% / 98%
maximum-number-of-achievable-transfer-requests
0
1
Here\'s how the code works:\n\n1. We use a brute-force approach to find the maximum number of achievable requests (`cnt`). It starts by considering the maximum possible number of requests (`len(requests)`), and decrementing `cnt` until either a solution is found or we exhaust all possibilities.\n\n1. We iterate in reverse order over the range from 1 to `len(requests)`. For each iteration, we consider all combinations of requests with the given count. \n\n1. For each combination, we unzip combinations to lists of`to`and`frm`. If`to`and`frm` have the same elements for some combination (which we check with `sorted(to) == sorted(frm)`) then we return`cnt`as the solution. If no such combination exists, we return 0.\n```\nclass Solution:\n def maximumRequests(self, n: int, requests: List[List[int]]) -> int:\n\n for cnt in reversed(range(1, len(requests)+1)):\n \n for com in combinations(requests,cnt):\n to, frm = map(sorted,zip(*com))\n if sorted(to) == sorted(frm): return cnt\n\n return 0\n```\n[https://leetcode.com/problems/maximum-number-of-achievable-transfer-requests/submissions/988756024/](http://)\n\nPython 3 || 5 lines, combinations, w/ explanation || T/M: 91% / 98%\n\nI could be wrong, but I think that time complexity (worst case) is *O*(2^*M* * *MN*log*N*) and space complexity is *O*(*M*), in which *M* ~ `len(requests)` and *N* ~ `n`.
3
You are given an integer array `jobs`, where `jobs[i]` is the amount of time it takes to complete the `ith` job. There are `k` workers that you can assign jobs to. Each job should be assigned to **exactly** one worker. The **working time** of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the **maximum working time** of any worker is **minimized**. _Return the **minimum** possible **maximum working time** of any assignment._ **Example 1:** **Input:** jobs = \[3,2,3\], k = 3 **Output:** 3 **Explanation:** By assigning each person one job, the maximum time is 3. **Example 2:** **Input:** jobs = \[1,2,4,7,8\], k = 2 **Output:** 11 **Explanation:** Assign the jobs the following way: Worker 1: 1, 2, 8 (working time = 1 + 2 + 8 = 11) Worker 2: 4, 7 (working time = 4 + 7 = 11) The maximum working time is 11. **Constraints:** * `1 <= k <= jobs.length <= 12` * `1 <= jobs[i] <= 107`
Think brute force When is a subset of requests okay?
EASY PYTHON SOLUTION || BACKTRACKING || DP
maximum-number-of-achievable-transfer-requests
0
1
# Code\n```\nclass Solution:\n def dp(self,i,lst,requests,n,dct):\n if i<0:\n if lst[:]==[0]*n:\n return 0\n return float("-infinity")\n if (i,tuple(lst)) in dct:\n return dct[(i,tuple(lst))]\n frm=requests[i][0]\n to=requests[i][1]\n lst[frm]-=1\n lst[to]+=1\n x=self.dp(i-1,lst,requests,n,dct)+1\n lst[frm]+=1\n lst[to]-=1\n y=self.dp(i-1,lst,requests,n,dct)\n dct[(i,tuple(lst))]=max(x,y)\n return max(x,y)\n\n\n def maximumRequests(self, n: int, requests: List[List[int]]) -> int:\n lst=[0]*n\n m=len(requests)\n ans=self.dp(m-1,lst,requests,n,{})\n if ans==float("-infinity"):\n return -1\n return ans\n```
3
We have `n` buildings numbered from `0` to `n - 1`. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in. You are given an array `requests` where `requests[i] = [fromi, toi]` represents an employee's request to transfer from building `fromi` to building `toi`. **All buildings are full**, so a list of requests is achievable only if for each building, the **net change in employee transfers is zero**. This means the number of employees **leaving** is **equal** to the number of employees **moving in**. For example if `n = 3` and two employees are leaving building `0`, one is leaving building `1`, and one is leaving building `2`, there should be two employees moving to building `0`, one employee moving to building `1`, and one employee moving to building `2`. Return _the maximum number of achievable requests_. **Example 1:** **Input:** n = 5, requests = \[\[0,1\],\[1,0\],\[0,1\],\[1,2\],\[2,0\],\[3,4\]\] **Output:** 5 **Explantion:** Let's see the requests: From building 0 we have employees x and y and both want to move to building 1. From building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively. From building 2 we have employee z and they want to move to building 0. From building 3 we have employee c and they want to move to building 4. From building 4 we don't have any requests. We can achieve the requests of users x and b by swapping their places. We can achieve the requests of users y, a and z by swapping the places in the 3 buildings. **Example 2:** **Input:** n = 3, requests = \[\[0,0\],\[1,2\],\[2,1\]\] **Output:** 3 **Explantion:** Let's see the requests: From building 0 we have employee x and they want to stay in the same building 0. From building 1 we have employee y and they want to move to building 2. From building 2 we have employee z and they want to move to building 1. We can achieve all the requests. **Example 3:** **Input:** n = 4, requests = \[\[0,3\],\[3,1\],\[1,2\],\[2,0\]\] **Output:** 4 **Constraints:** * `1 <= n <= 20` * `1 <= requests.length <= 16` * `requests[i].length == 2` * `0 <= fromi, toi < n`
null
EASY PYTHON SOLUTION || BACKTRACKING || DP
maximum-number-of-achievable-transfer-requests
0
1
# Code\n```\nclass Solution:\n def dp(self,i,lst,requests,n,dct):\n if i<0:\n if lst[:]==[0]*n:\n return 0\n return float("-infinity")\n if (i,tuple(lst)) in dct:\n return dct[(i,tuple(lst))]\n frm=requests[i][0]\n to=requests[i][1]\n lst[frm]-=1\n lst[to]+=1\n x=self.dp(i-1,lst,requests,n,dct)+1\n lst[frm]+=1\n lst[to]-=1\n y=self.dp(i-1,lst,requests,n,dct)\n dct[(i,tuple(lst))]=max(x,y)\n return max(x,y)\n\n\n def maximumRequests(self, n: int, requests: List[List[int]]) -> int:\n lst=[0]*n\n m=len(requests)\n ans=self.dp(m-1,lst,requests,n,{})\n if ans==float("-infinity"):\n return -1\n return ans\n```
3
You are given an integer array `jobs`, where `jobs[i]` is the amount of time it takes to complete the `ith` job. There are `k` workers that you can assign jobs to. Each job should be assigned to **exactly** one worker. The **working time** of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the **maximum working time** of any worker is **minimized**. _Return the **minimum** possible **maximum working time** of any assignment._ **Example 1:** **Input:** jobs = \[3,2,3\], k = 3 **Output:** 3 **Explanation:** By assigning each person one job, the maximum time is 3. **Example 2:** **Input:** jobs = \[1,2,4,7,8\], k = 2 **Output:** 11 **Explanation:** Assign the jobs the following way: Worker 1: 1, 2, 8 (working time = 1 + 2 + 8 = 11) Worker 2: 4, 7 (working time = 4 + 7 = 11) The maximum working time is 11. **Constraints:** * `1 <= k <= jobs.length <= 12` * `1 <= jobs[i] <= 107`
Think brute force When is a subset of requests okay?
Easy Python Solution, similar to 78. Subsets
maximum-number-of-achievable-transfer-requests
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nSimilar approach as Subset, Subset ii\n\nFor each request, we can choose to pick it or not. Once both indegree and outdegree for each building are balanced, we record it and update the maximum request.\n\nI don\'t want to use combination() function during an interview. \n\n# Code for 78. Subset\n```\nclass Solution(object):\n def subsetsWithDup(self, nums):\n \n res = []\n nums.sort()\n\n def recur(index,curPath):\n res.append(curPath[:])\n if index == len(nums):\n return\n \n for i in range(index,len(nums)):\n if i > index and nums[i]==nums[i-1]:\n continue\n curPath.append(nums[i])\n recur(i+1,curPath)\n curPath.pop()\n \n recur(0,[])\n return res\n```\n# Code\n```\nclass Solution(object):\n def maximumRequests(self, n, requests):\n """\n :type n: int\n :type requests: List[List[int]]\n :rtype: int\n """\n l = len(requests)\n buildings = [0 for i in range(n)]\n self.res = 0\n\n def recur(index,cur,buildings):\n if all(e==0 for e in buildings):\n self.res = max(self.res,cur)\n if index == len(requests):\n return\n \n for i in range(index,l):\n src,dest = requests[i]\n buildings[src] -= 1\n buildings[dest] += 1\n\n recur(i+1,cur+1,buildings)\n\n buildings[src] += 1\n buildings[dest] -= 1\n \n recur(0,0,buildings)\n return self.res\n\n \n```
2
We have `n` buildings numbered from `0` to `n - 1`. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in. You are given an array `requests` where `requests[i] = [fromi, toi]` represents an employee's request to transfer from building `fromi` to building `toi`. **All buildings are full**, so a list of requests is achievable only if for each building, the **net change in employee transfers is zero**. This means the number of employees **leaving** is **equal** to the number of employees **moving in**. For example if `n = 3` and two employees are leaving building `0`, one is leaving building `1`, and one is leaving building `2`, there should be two employees moving to building `0`, one employee moving to building `1`, and one employee moving to building `2`. Return _the maximum number of achievable requests_. **Example 1:** **Input:** n = 5, requests = \[\[0,1\],\[1,0\],\[0,1\],\[1,2\],\[2,0\],\[3,4\]\] **Output:** 5 **Explantion:** Let's see the requests: From building 0 we have employees x and y and both want to move to building 1. From building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively. From building 2 we have employee z and they want to move to building 0. From building 3 we have employee c and they want to move to building 4. From building 4 we don't have any requests. We can achieve the requests of users x and b by swapping their places. We can achieve the requests of users y, a and z by swapping the places in the 3 buildings. **Example 2:** **Input:** n = 3, requests = \[\[0,0\],\[1,2\],\[2,1\]\] **Output:** 3 **Explantion:** Let's see the requests: From building 0 we have employee x and they want to stay in the same building 0. From building 1 we have employee y and they want to move to building 2. From building 2 we have employee z and they want to move to building 1. We can achieve all the requests. **Example 3:** **Input:** n = 4, requests = \[\[0,3\],\[3,1\],\[1,2\],\[2,0\]\] **Output:** 4 **Constraints:** * `1 <= n <= 20` * `1 <= requests.length <= 16` * `requests[i].length == 2` * `0 <= fromi, toi < n`
null
Easy Python Solution, similar to 78. Subsets
maximum-number-of-achievable-transfer-requests
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nSimilar approach as Subset, Subset ii\n\nFor each request, we can choose to pick it or not. Once both indegree and outdegree for each building are balanced, we record it and update the maximum request.\n\nI don\'t want to use combination() function during an interview. \n\n# Code for 78. Subset\n```\nclass Solution(object):\n def subsetsWithDup(self, nums):\n \n res = []\n nums.sort()\n\n def recur(index,curPath):\n res.append(curPath[:])\n if index == len(nums):\n return\n \n for i in range(index,len(nums)):\n if i > index and nums[i]==nums[i-1]:\n continue\n curPath.append(nums[i])\n recur(i+1,curPath)\n curPath.pop()\n \n recur(0,[])\n return res\n```\n# Code\n```\nclass Solution(object):\n def maximumRequests(self, n, requests):\n """\n :type n: int\n :type requests: List[List[int]]\n :rtype: int\n """\n l = len(requests)\n buildings = [0 for i in range(n)]\n self.res = 0\n\n def recur(index,cur,buildings):\n if all(e==0 for e in buildings):\n self.res = max(self.res,cur)\n if index == len(requests):\n return\n \n for i in range(index,l):\n src,dest = requests[i]\n buildings[src] -= 1\n buildings[dest] += 1\n\n recur(i+1,cur+1,buildings)\n\n buildings[src] += 1\n buildings[dest] -= 1\n \n recur(0,0,buildings)\n return self.res\n\n \n```
2
You are given an integer array `jobs`, where `jobs[i]` is the amount of time it takes to complete the `ith` job. There are `k` workers that you can assign jobs to. Each job should be assigned to **exactly** one worker. The **working time** of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the **maximum working time** of any worker is **minimized**. _Return the **minimum** possible **maximum working time** of any assignment._ **Example 1:** **Input:** jobs = \[3,2,3\], k = 3 **Output:** 3 **Explanation:** By assigning each person one job, the maximum time is 3. **Example 2:** **Input:** jobs = \[1,2,4,7,8\], k = 2 **Output:** 11 **Explanation:** Assign the jobs the following way: Worker 1: 1, 2, 8 (working time = 1 + 2 + 8 = 11) Worker 2: 4, 7 (working time = 4 + 7 = 11) The maximum working time is 11. **Constraints:** * `1 <= k <= jobs.length <= 12` * `1 <= jobs[i] <= 107`
Think brute force When is a subset of requests okay?
Python3 Solution
maximum-number-of-achievable-transfer-requests
0
1
\n```\nclass Solution:\n def maximumRequests(self, n: int, requests: List[List[int]]) -> int:\n l=len(requests)\n for i in range(l,0,-1):\n for j in combinations(requests,i):\n if Counter(x for x ,y in j)==Counter(y for x,y in j):\n return i\n\n return 0 \n```
2
We have `n` buildings numbered from `0` to `n - 1`. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in. You are given an array `requests` where `requests[i] = [fromi, toi]` represents an employee's request to transfer from building `fromi` to building `toi`. **All buildings are full**, so a list of requests is achievable only if for each building, the **net change in employee transfers is zero**. This means the number of employees **leaving** is **equal** to the number of employees **moving in**. For example if `n = 3` and two employees are leaving building `0`, one is leaving building `1`, and one is leaving building `2`, there should be two employees moving to building `0`, one employee moving to building `1`, and one employee moving to building `2`. Return _the maximum number of achievable requests_. **Example 1:** **Input:** n = 5, requests = \[\[0,1\],\[1,0\],\[0,1\],\[1,2\],\[2,0\],\[3,4\]\] **Output:** 5 **Explantion:** Let's see the requests: From building 0 we have employees x and y and both want to move to building 1. From building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively. From building 2 we have employee z and they want to move to building 0. From building 3 we have employee c and they want to move to building 4. From building 4 we don't have any requests. We can achieve the requests of users x and b by swapping their places. We can achieve the requests of users y, a and z by swapping the places in the 3 buildings. **Example 2:** **Input:** n = 3, requests = \[\[0,0\],\[1,2\],\[2,1\]\] **Output:** 3 **Explantion:** Let's see the requests: From building 0 we have employee x and they want to stay in the same building 0. From building 1 we have employee y and they want to move to building 2. From building 2 we have employee z and they want to move to building 1. We can achieve all the requests. **Example 3:** **Input:** n = 4, requests = \[\[0,3\],\[3,1\],\[1,2\],\[2,0\]\] **Output:** 4 **Constraints:** * `1 <= n <= 20` * `1 <= requests.length <= 16` * `requests[i].length == 2` * `0 <= fromi, toi < n`
null
Python3 Solution
maximum-number-of-achievable-transfer-requests
0
1
\n```\nclass Solution:\n def maximumRequests(self, n: int, requests: List[List[int]]) -> int:\n l=len(requests)\n for i in range(l,0,-1):\n for j in combinations(requests,i):\n if Counter(x for x ,y in j)==Counter(y for x,y in j):\n return i\n\n return 0 \n```
2
You are given an integer array `jobs`, where `jobs[i]` is the amount of time it takes to complete the `ith` job. There are `k` workers that you can assign jobs to. Each job should be assigned to **exactly** one worker. The **working time** of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the **maximum working time** of any worker is **minimized**. _Return the **minimum** possible **maximum working time** of any assignment._ **Example 1:** **Input:** jobs = \[3,2,3\], k = 3 **Output:** 3 **Explanation:** By assigning each person one job, the maximum time is 3. **Example 2:** **Input:** jobs = \[1,2,4,7,8\], k = 2 **Output:** 11 **Explanation:** Assign the jobs the following way: Worker 1: 1, 2, 8 (working time = 1 + 2 + 8 = 11) Worker 2: 4, 7 (working time = 4 + 7 = 11) The maximum working time is 11. **Constraints:** * `1 <= k <= jobs.length <= 12` * `1 <= jobs[i] <= 107`
Think brute force When is a subset of requests okay?
Python short and clean. Also a 1-liner. Functional programming.
maximum-number-of-achievable-transfer-requests
0
1
# Approach\n1. Define a function `is_achievable` which returns `True` if the net change in employees transfer is zero after processing the given `reqs`.\nThis can be computed by, checking if the difference between the counts of `from(u)` and counts of `to(v)` is all zero.\n\n2. Generate the `powerset` of the `requests` list excluding the empty subset. Make sure to generate it in the order of decreasing set size. This gurantees the first `subset` with `is_achievable` is the one with max requests.\n\n3. Select(`filter`) the subsets which `is_achievable` and return the `len` of the first such subset.\n\n# Complexity\n- Time complexity: $$O(n \\cdot 2^m)$$\n\n- Space complexity: $$O(m)$$\n\nwhere, `m is number of requests`.\n\n# Code\nSplit into 3 lines for readability. Variables can be easily substituted to make it a 1-liner, albeit a really long one.\n```python\nclass Solution:\n def maximumRequests(self, n: int, requests: list[list[int]]) -> int:\n is_achievable = lambda reqs: not any((Counter(u for u, _ in reqs) - Counter(v for _, v in reqs)).values())\n powerset_reqs = chain.from_iterable(combinations(requests, k) for k in range(len(requests), 0, -1))\n return next(map(len, filter(is_achievable, powerset_reqs)), 0)\n\n\n```
2
We have `n` buildings numbered from `0` to `n - 1`. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in. You are given an array `requests` where `requests[i] = [fromi, toi]` represents an employee's request to transfer from building `fromi` to building `toi`. **All buildings are full**, so a list of requests is achievable only if for each building, the **net change in employee transfers is zero**. This means the number of employees **leaving** is **equal** to the number of employees **moving in**. For example if `n = 3` and two employees are leaving building `0`, one is leaving building `1`, and one is leaving building `2`, there should be two employees moving to building `0`, one employee moving to building `1`, and one employee moving to building `2`. Return _the maximum number of achievable requests_. **Example 1:** **Input:** n = 5, requests = \[\[0,1\],\[1,0\],\[0,1\],\[1,2\],\[2,0\],\[3,4\]\] **Output:** 5 **Explantion:** Let's see the requests: From building 0 we have employees x and y and both want to move to building 1. From building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively. From building 2 we have employee z and they want to move to building 0. From building 3 we have employee c and they want to move to building 4. From building 4 we don't have any requests. We can achieve the requests of users x and b by swapping their places. We can achieve the requests of users y, a and z by swapping the places in the 3 buildings. **Example 2:** **Input:** n = 3, requests = \[\[0,0\],\[1,2\],\[2,1\]\] **Output:** 3 **Explantion:** Let's see the requests: From building 0 we have employee x and they want to stay in the same building 0. From building 1 we have employee y and they want to move to building 2. From building 2 we have employee z and they want to move to building 1. We can achieve all the requests. **Example 3:** **Input:** n = 4, requests = \[\[0,3\],\[3,1\],\[1,2\],\[2,0\]\] **Output:** 4 **Constraints:** * `1 <= n <= 20` * `1 <= requests.length <= 16` * `requests[i].length == 2` * `0 <= fromi, toi < n`
null
Python short and clean. Also a 1-liner. Functional programming.
maximum-number-of-achievable-transfer-requests
0
1
# Approach\n1. Define a function `is_achievable` which returns `True` if the net change in employees transfer is zero after processing the given `reqs`.\nThis can be computed by, checking if the difference between the counts of `from(u)` and counts of `to(v)` is all zero.\n\n2. Generate the `powerset` of the `requests` list excluding the empty subset. Make sure to generate it in the order of decreasing set size. This gurantees the first `subset` with `is_achievable` is the one with max requests.\n\n3. Select(`filter`) the subsets which `is_achievable` and return the `len` of the first such subset.\n\n# Complexity\n- Time complexity: $$O(n \\cdot 2^m)$$\n\n- Space complexity: $$O(m)$$\n\nwhere, `m is number of requests`.\n\n# Code\nSplit into 3 lines for readability. Variables can be easily substituted to make it a 1-liner, albeit a really long one.\n```python\nclass Solution:\n def maximumRequests(self, n: int, requests: list[list[int]]) -> int:\n is_achievable = lambda reqs: not any((Counter(u for u, _ in reqs) - Counter(v for _, v in reqs)).values())\n powerset_reqs = chain.from_iterable(combinations(requests, k) for k in range(len(requests), 0, -1))\n return next(map(len, filter(is_achievable, powerset_reqs)), 0)\n\n\n```
2
You are given an integer array `jobs`, where `jobs[i]` is the amount of time it takes to complete the `ith` job. There are `k` workers that you can assign jobs to. Each job should be assigned to **exactly** one worker. The **working time** of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the **maximum working time** of any worker is **minimized**. _Return the **minimum** possible **maximum working time** of any assignment._ **Example 1:** **Input:** jobs = \[3,2,3\], k = 3 **Output:** 3 **Explanation:** By assigning each person one job, the maximum time is 3. **Example 2:** **Input:** jobs = \[1,2,4,7,8\], k = 2 **Output:** 11 **Explanation:** Assign the jobs the following way: Worker 1: 1, 2, 8 (working time = 1 + 2 + 8 = 11) Worker 2: 4, 7 (working time = 4 + 7 = 11) The maximum working time is 11. **Constraints:** * `1 <= k <= jobs.length <= 12` * `1 <= jobs[i] <= 107`
Think brute force When is a subset of requests okay?
🐍 Combinations.py ---> Python is OP.........🔥
maximum-number-of-achievable-transfer-requests
0
1
<h1>DO UPVOTE\uD83D\uDD25\n\n# Approach\nTrying Every Combination\n\n# Complexity\n- Time complexity:\n$$O(2^n)$$ \n\n\n![](https://media.makeameme.org/created/leetcode-contests-these.jpg)\n\n\n# Code\n```\nclass Solution:\n def maximumRequests(self, n: int, r: List[List[int]]) -> int:\n same=0\n req=[]\n #if both moving to same building\n for i in r:\n if i[0]==i[1]:same+=1\n else:req.append(i)\n ans=0\n for i in range(len(req)+1):\n for combs in list(itertools.combinations(req,i)):\n if combs:\n temp=[0]*n\n for at in combs:\n temp[at[0]]+=1\n temp[at[1]]-=1\n if set(temp)=={0}:\n print(combs)\n ans=max(ans,len(combs))\n return ans+same\n\n\n```
2
We have `n` buildings numbered from `0` to `n - 1`. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in. You are given an array `requests` where `requests[i] = [fromi, toi]` represents an employee's request to transfer from building `fromi` to building `toi`. **All buildings are full**, so a list of requests is achievable only if for each building, the **net change in employee transfers is zero**. This means the number of employees **leaving** is **equal** to the number of employees **moving in**. For example if `n = 3` and two employees are leaving building `0`, one is leaving building `1`, and one is leaving building `2`, there should be two employees moving to building `0`, one employee moving to building `1`, and one employee moving to building `2`. Return _the maximum number of achievable requests_. **Example 1:** **Input:** n = 5, requests = \[\[0,1\],\[1,0\],\[0,1\],\[1,2\],\[2,0\],\[3,4\]\] **Output:** 5 **Explantion:** Let's see the requests: From building 0 we have employees x and y and both want to move to building 1. From building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively. From building 2 we have employee z and they want to move to building 0. From building 3 we have employee c and they want to move to building 4. From building 4 we don't have any requests. We can achieve the requests of users x and b by swapping their places. We can achieve the requests of users y, a and z by swapping the places in the 3 buildings. **Example 2:** **Input:** n = 3, requests = \[\[0,0\],\[1,2\],\[2,1\]\] **Output:** 3 **Explantion:** Let's see the requests: From building 0 we have employee x and they want to stay in the same building 0. From building 1 we have employee y and they want to move to building 2. From building 2 we have employee z and they want to move to building 1. We can achieve all the requests. **Example 3:** **Input:** n = 4, requests = \[\[0,3\],\[3,1\],\[1,2\],\[2,0\]\] **Output:** 4 **Constraints:** * `1 <= n <= 20` * `1 <= requests.length <= 16` * `requests[i].length == 2` * `0 <= fromi, toi < n`
null
🐍 Combinations.py ---> Python is OP.........🔥
maximum-number-of-achievable-transfer-requests
0
1
<h1>DO UPVOTE\uD83D\uDD25\n\n# Approach\nTrying Every Combination\n\n# Complexity\n- Time complexity:\n$$O(2^n)$$ \n\n\n![](https://media.makeameme.org/created/leetcode-contests-these.jpg)\n\n\n# Code\n```\nclass Solution:\n def maximumRequests(self, n: int, r: List[List[int]]) -> int:\n same=0\n req=[]\n #if both moving to same building\n for i in r:\n if i[0]==i[1]:same+=1\n else:req.append(i)\n ans=0\n for i in range(len(req)+1):\n for combs in list(itertools.combinations(req,i)):\n if combs:\n temp=[0]*n\n for at in combs:\n temp[at[0]]+=1\n temp[at[1]]-=1\n if set(temp)=={0}:\n print(combs)\n ans=max(ans,len(combs))\n return ans+same\n\n\n```
2
You are given an integer array `jobs`, where `jobs[i]` is the amount of time it takes to complete the `ith` job. There are `k` workers that you can assign jobs to. Each job should be assigned to **exactly** one worker. The **working time** of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the **maximum working time** of any worker is **minimized**. _Return the **minimum** possible **maximum working time** of any assignment._ **Example 1:** **Input:** jobs = \[3,2,3\], k = 3 **Output:** 3 **Explanation:** By assigning each person one job, the maximum time is 3. **Example 2:** **Input:** jobs = \[1,2,4,7,8\], k = 2 **Output:** 11 **Explanation:** Assign the jobs the following way: Worker 1: 1, 2, 8 (working time = 1 + 2 + 8 = 11) Worker 2: 4, 7 (working time = 4 + 7 = 11) The maximum working time is 11. **Constraints:** * `1 <= k <= jobs.length <= 12` * `1 <= jobs[i] <= 107`
Think brute force When is a subset of requests okay?
✅Back Track🔥 || C++ || JAVA || PYTHON || Beginner Friendly🔥🔥🔥
maximum-number-of-achievable-transfer-requests
1
1
# Intuition:\n\nThe Intuition is to use backtracking approach to explore all possible combinations of taking or not taking transfer requests. It maintains a count of transfer requests and checks if the requests are balanced for each building. The maximum count of transfer requests that satisfies the balanced request condition is returned as the result.\n\n# Explanation:\n\n1. The `maximumRequests` function takes an integer `n` representing the number of buildings and a 2D vector `requests` containing the transfer requests.\n2. The function initializes a vector `indegree` of size `n` to keep track of the difference between incoming and outgoing requests for each building. Initially, all values are set to 0.\n3. The function then calls the `helper` function with the starting index as 0, the `requests` vector, the `indegree` vector, `n`, and a count variable set to 0.\n4. The `helper` function is the main backtracking function. It takes the current `start` index, the `requests` vector, the `indegree` vector, `n`, and the current `count` of transfer requests.\n5. If the `start` index is equal to the size of the `requests` vector, it means we have processed all transfer requests. In this case, the function checks if all buildings have balanced requests (i.e., `indegree` values are all 0). If so, it updates the `ans` variable with the maximum count of transfer requests.\n6. If the `start` index is not equal to the size of the `requests` vector, the function has two choices: take or not take the current transfer request.\n7. If we take the current transfer request, we reduce the `indegree` value of the source building (`requests[start][0]`) by 1 and increase the `indegree` value of the destination building (`requests[start][1]`) by 1. Then, we recursively call the `helper` function with the updated `start` index, `requests`, `indegree`, `n`, and the incremented `count` by 1.\n8. After the recursive call, we revert the changes made in step 7 by increasing the `indegree` value of the source building and decreasing the `indegree` value of the destination building. This step represents the "not-take" choice. We then recursively call the `helper` function with the updated `start` index, `requests`, `indegree`, `n`, and the same `count` value.\n9. The `helper` function explores all possible combinations of taking or not taking transfer requests, tracking the maximum count of transfer requests (`ans`) that satisfies the balanced request condition.\n10. Finally, the `maximumRequests` function returns the maximum count of transfer requests stored in the `ans` variable.\n\n# Complexity:\n**Time complexity:** $$ O(2^M * N) $$\n**Space complexity:** $$ O(N + M) $$\nN is the number of buildings, and M is the number of requests.\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int ans = 0;\n\n void helper(int start, vector<vector<int>>& requests, vector<int>& indegree, int n, int count) {\n if (start == requests.size()) {\n for (int i = 0; i < n; i++) {\n if (indegree[i] != 0) {\n return;\n }\n }\n ans = max(ans, count);\n return;\n }\n\n // Take \n indegree[requests[start][0]]--;\n indegree[requests[start][1]]++;\n helper(start + 1,requests, indegree, n, count + 1);\n\n // Not-take\n indegree[requests[start][0]]++;\n indegree[requests[start][1]]--;\n helper(start + 1,requests, indegree, n, count);\n }\n \n int maximumRequests(int n, vector<vector<int>>& requests) {\n vector<int> indegree(n, 0);\n helper(0, requests, indegree, n, 0);\n return ans;\n }\n};\n```\n```Java []\nclass Solution {\n public int maximumRequests(int n, int[][] requests) {\n int[] indegree = new int[n];\n return helper(0, requests, indegree, n, 0);\n }\n\n public int helper(int start, int[][] requests, int[] indegree, int n, int count) {\n if (start == requests.length) {\n for (int i = 0; i < n; i++) {\n if (indegree[i] != 0) {\n return 0;\n }\n }\n return count;\n }\n\n // Take \n indegree[requests[start][0]]--;\n indegree[requests[start][1]]++;\n int take = helper(start + 1, requests, indegree, n, count + 1);\n\n // Not-take\n indegree[requests[start][0]]++;\n indegree[requests[start][1]]--;\n int notTake = helper(start + 1, requests, indegree, n, count);\n\n return Math.max(take, notTake);\n }\n}\n```\n```Python []\nclass Solution:\n def __init__(self):\n self.ans = 0\n\n def helper(self, start, requests, indegree, n, count):\n if start == len(requests):\n for i in range(n):\n if indegree[i] != 0:\n return\n self.ans = max(self.ans, count)\n return\n\n # Take \n indegree[requests[start][0]] -= 1\n indegree[requests[start][1]] += 1\n self.helper(start + 1, requests, indegree, n, count + 1)\n\n # Not-take\n indegree[requests[start][0]] += 1\n indegree[requests[start][1]] -= 1\n self.helper(start + 1, requests, indegree, n, count)\n\n def maximumRequests(self, n, requests):\n indegree = [0] * n\n self.helper(0, requests, indegree, n, 0)\n return self.ans\n```\n\n![CUTE_CAT.png](https://assets.leetcode.com/users/images/08f772be-c314-40e3-955a-b29845257985_1688259472.2231731.png)\n\n\n**If you found my solution helpful, I would greatly appreciate your upvote, as it would motivate me to continue sharing more solutions.**
148
We have `n` buildings numbered from `0` to `n - 1`. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in. You are given an array `requests` where `requests[i] = [fromi, toi]` represents an employee's request to transfer from building `fromi` to building `toi`. **All buildings are full**, so a list of requests is achievable only if for each building, the **net change in employee transfers is zero**. This means the number of employees **leaving** is **equal** to the number of employees **moving in**. For example if `n = 3` and two employees are leaving building `0`, one is leaving building `1`, and one is leaving building `2`, there should be two employees moving to building `0`, one employee moving to building `1`, and one employee moving to building `2`. Return _the maximum number of achievable requests_. **Example 1:** **Input:** n = 5, requests = \[\[0,1\],\[1,0\],\[0,1\],\[1,2\],\[2,0\],\[3,4\]\] **Output:** 5 **Explantion:** Let's see the requests: From building 0 we have employees x and y and both want to move to building 1. From building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively. From building 2 we have employee z and they want to move to building 0. From building 3 we have employee c and they want to move to building 4. From building 4 we don't have any requests. We can achieve the requests of users x and b by swapping their places. We can achieve the requests of users y, a and z by swapping the places in the 3 buildings. **Example 2:** **Input:** n = 3, requests = \[\[0,0\],\[1,2\],\[2,1\]\] **Output:** 3 **Explantion:** Let's see the requests: From building 0 we have employee x and they want to stay in the same building 0. From building 1 we have employee y and they want to move to building 2. From building 2 we have employee z and they want to move to building 1. We can achieve all the requests. **Example 3:** **Input:** n = 4, requests = \[\[0,3\],\[3,1\],\[1,2\],\[2,0\]\] **Output:** 4 **Constraints:** * `1 <= n <= 20` * `1 <= requests.length <= 16` * `requests[i].length == 2` * `0 <= fromi, toi < n`
null
✅Back Track🔥 || C++ || JAVA || PYTHON || Beginner Friendly🔥🔥🔥
maximum-number-of-achievable-transfer-requests
1
1
# Intuition:\n\nThe Intuition is to use backtracking approach to explore all possible combinations of taking or not taking transfer requests. It maintains a count of transfer requests and checks if the requests are balanced for each building. The maximum count of transfer requests that satisfies the balanced request condition is returned as the result.\n\n# Explanation:\n\n1. The `maximumRequests` function takes an integer `n` representing the number of buildings and a 2D vector `requests` containing the transfer requests.\n2. The function initializes a vector `indegree` of size `n` to keep track of the difference between incoming and outgoing requests for each building. Initially, all values are set to 0.\n3. The function then calls the `helper` function with the starting index as 0, the `requests` vector, the `indegree` vector, `n`, and a count variable set to 0.\n4. The `helper` function is the main backtracking function. It takes the current `start` index, the `requests` vector, the `indegree` vector, `n`, and the current `count` of transfer requests.\n5. If the `start` index is equal to the size of the `requests` vector, it means we have processed all transfer requests. In this case, the function checks if all buildings have balanced requests (i.e., `indegree` values are all 0). If so, it updates the `ans` variable with the maximum count of transfer requests.\n6. If the `start` index is not equal to the size of the `requests` vector, the function has two choices: take or not take the current transfer request.\n7. If we take the current transfer request, we reduce the `indegree` value of the source building (`requests[start][0]`) by 1 and increase the `indegree` value of the destination building (`requests[start][1]`) by 1. Then, we recursively call the `helper` function with the updated `start` index, `requests`, `indegree`, `n`, and the incremented `count` by 1.\n8. After the recursive call, we revert the changes made in step 7 by increasing the `indegree` value of the source building and decreasing the `indegree` value of the destination building. This step represents the "not-take" choice. We then recursively call the `helper` function with the updated `start` index, `requests`, `indegree`, `n`, and the same `count` value.\n9. The `helper` function explores all possible combinations of taking or not taking transfer requests, tracking the maximum count of transfer requests (`ans`) that satisfies the balanced request condition.\n10. Finally, the `maximumRequests` function returns the maximum count of transfer requests stored in the `ans` variable.\n\n# Complexity:\n**Time complexity:** $$ O(2^M * N) $$\n**Space complexity:** $$ O(N + M) $$\nN is the number of buildings, and M is the number of requests.\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int ans = 0;\n\n void helper(int start, vector<vector<int>>& requests, vector<int>& indegree, int n, int count) {\n if (start == requests.size()) {\n for (int i = 0; i < n; i++) {\n if (indegree[i] != 0) {\n return;\n }\n }\n ans = max(ans, count);\n return;\n }\n\n // Take \n indegree[requests[start][0]]--;\n indegree[requests[start][1]]++;\n helper(start + 1,requests, indegree, n, count + 1);\n\n // Not-take\n indegree[requests[start][0]]++;\n indegree[requests[start][1]]--;\n helper(start + 1,requests, indegree, n, count);\n }\n \n int maximumRequests(int n, vector<vector<int>>& requests) {\n vector<int> indegree(n, 0);\n helper(0, requests, indegree, n, 0);\n return ans;\n }\n};\n```\n```Java []\nclass Solution {\n public int maximumRequests(int n, int[][] requests) {\n int[] indegree = new int[n];\n return helper(0, requests, indegree, n, 0);\n }\n\n public int helper(int start, int[][] requests, int[] indegree, int n, int count) {\n if (start == requests.length) {\n for (int i = 0; i < n; i++) {\n if (indegree[i] != 0) {\n return 0;\n }\n }\n return count;\n }\n\n // Take \n indegree[requests[start][0]]--;\n indegree[requests[start][1]]++;\n int take = helper(start + 1, requests, indegree, n, count + 1);\n\n // Not-take\n indegree[requests[start][0]]++;\n indegree[requests[start][1]]--;\n int notTake = helper(start + 1, requests, indegree, n, count);\n\n return Math.max(take, notTake);\n }\n}\n```\n```Python []\nclass Solution:\n def __init__(self):\n self.ans = 0\n\n def helper(self, start, requests, indegree, n, count):\n if start == len(requests):\n for i in range(n):\n if indegree[i] != 0:\n return\n self.ans = max(self.ans, count)\n return\n\n # Take \n indegree[requests[start][0]] -= 1\n indegree[requests[start][1]] += 1\n self.helper(start + 1, requests, indegree, n, count + 1)\n\n # Not-take\n indegree[requests[start][0]] += 1\n indegree[requests[start][1]] -= 1\n self.helper(start + 1, requests, indegree, n, count)\n\n def maximumRequests(self, n, requests):\n indegree = [0] * n\n self.helper(0, requests, indegree, n, 0)\n return self.ans\n```\n\n![CUTE_CAT.png](https://assets.leetcode.com/users/images/08f772be-c314-40e3-955a-b29845257985_1688259472.2231731.png)\n\n\n**If you found my solution helpful, I would greatly appreciate your upvote, as it would motivate me to continue sharing more solutions.**
148
You are given an integer array `jobs`, where `jobs[i]` is the amount of time it takes to complete the `ith` job. There are `k` workers that you can assign jobs to. Each job should be assigned to **exactly** one worker. The **working time** of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the **maximum working time** of any worker is **minimized**. _Return the **minimum** possible **maximum working time** of any assignment._ **Example 1:** **Input:** jobs = \[3,2,3\], k = 3 **Output:** 3 **Explanation:** By assigning each person one job, the maximum time is 3. **Example 2:** **Input:** jobs = \[1,2,4,7,8\], k = 2 **Output:** 11 **Explanation:** Assign the jobs the following way: Worker 1: 1, 2, 8 (working time = 1 + 2 + 8 = 11) Worker 2: 4, 7 (working time = 4 + 7 = 11) The maximum working time is 11. **Constraints:** * `1 <= k <= jobs.length <= 12` * `1 <= jobs[i] <= 107`
Think brute force When is a subset of requests okay?
✅C++|| Java || Python || Solution using Backtracking (faster 80.39%(98 ms), memory 100%(8.6 mb))
maximum-number-of-achievable-transfer-requests
1
1
\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n\n\nThe `maximumRequests` function initializes a vector `v` of size `n` with all elements initialized to 0. This vector represents the current state of the buildings. Each element in the vector represents the net change in the number of requests for a particular building. Positive values indicate that there are more requests for that building, while negative values indicate that there are more requests to leave that building.\n\nThe function then calls a helper function `helper` with the initial index set to 0. The `helper` function is a recursive function that tries to fulfill each request and computes the maximum number of requests that can be fulfilled.\n\nIn the `helper` function, if the index reaches the end of the requests vector (`index == requests.size()`), it checks if all buildings have zero net requests. If they do, it returns 0, indicating that all requests have been fulfilled. Otherwise, it returns a large negative value `INT_MIN`, indicating that this state is not valid.\n\nIf the index is not at the end of the requests vector, the function proceeds to handle the current request. It decreases the net request count for the building at `requests[index][0]` and increases the count for the building at `requests[index][1]`. It then recursively calls the `helper` function with the index incremented by 1.\n\nAfter the recursive call, the function restores the net request counts for the current request by increasing the count for the building at `requests[index][0]` and decreasing the count for the building at `requests[index][1]`. This is done to backtrack and consider other possible combinations of requests.\n\nThe function then calculates two values: `take` and `notTake`. `take` represents the maximum number of requests that can be fulfilled if the current request is taken into account. It adds 1 to the result of the recursive call (`1 + helper(index + 1, n, requests, v)`).\n\n`notTake` represents the maximum number of requests that can be fulfilled if the current request is not taken into account. It calls the recursive function without changing the net request counts (`helper(index + 1, n, requests, v)`).\n\nFinally, the function returns the maximum value between `take` and `notTake`, representing the maximum number of requests that can be fulfilled considering the current state.\n\n\n\n# Code\n\n# C++\n```\nclass Solution {\n \n\n int helper(int index, int n,vector<vector<int>>& requests,vector<int> &v){\n\n if(index==requests.size()){\n for(int i=0;i<n;i++){\n if(v[i]!=0) return INT_MIN;\n }\n return 0;\n }\n\n v[requests[index][0]]-=1;\n v[requests[index][1]]+=1;\n int take=1+helper(index+1,n,requests,v);\n v[requests[index][0]]+=1;\n v[requests[index][1]]-=1;\n int notTake=helper(index+1,n,requests,v);\n\n\n return max(take,notTake);\n }\n\n\npublic:\n int maximumRequests(int n, vector<vector<int>>& requests) {\n vector<int> v(n,0);\n return helper(0,n, requests,v);\n }\n};\n```\n# Java\n```\nclass Solution {\n private int helper(int index, int n, List<List<Integer>> requests, List<Integer> v) {\n if (index == requests.size()) {\n for (int i = 0; i < n; i++) {\n if (v.get(i) != 0)\n return Integer.MIN_VALUE;\n }\n return 0;\n }\n \n v.set(requests.get(index).get(0), v.get(requests.get(index).get(0)) - 1);\n v.set(requests.get(index).get(1), v.get(requests.get(index).get(1)) + 1);\n int take = 1 + helper(index + 1, n, requests, v);\n v.set(requests.get(index).get(0), v.get(requests.get(index).get(0)) + 1);\n v.set(requests.get(index).get(1), v.get(requests.get(index).get(1)) - 1);\n int notTake = helper(index + 1, n, requests, v);\n \n return Math.max(take, notTake);\n }\n \n public int maximumRequests(int n, List<List<Integer>> requests) {\n List<Integer> v = new ArrayList<>(n);\n for (int i = 0; i < n; i++) {\n v.add(0);\n }\n return helper(0, n, requests, v);\n }\n}\n\n```\n\n# Python\n\n```\nclass Solution:\n def helper(self, index, n, requests, v):\n if index == len(requests):\n for i in range(n):\n if v[i] != 0:\n return float(\'-inf\')\n return 0\n\n v[requests[index][0]] -= 1\n v[requests[index][1]] += 1\n take = 1 + self.helper(index + 1, n, requests, v)\n v[requests[index][0]] += 1\n v[requests[index][1]] -= 1\n notTake = self.helper(index + 1, n, requests, v)\n\n return max(take, notTake)\n\n def maximumRequests(self, n, requests):\n v = [0] * n\n return self.helper(0, n, requests, v)\n\n```
1
We have `n` buildings numbered from `0` to `n - 1`. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in. You are given an array `requests` where `requests[i] = [fromi, toi]` represents an employee's request to transfer from building `fromi` to building `toi`. **All buildings are full**, so a list of requests is achievable only if for each building, the **net change in employee transfers is zero**. This means the number of employees **leaving** is **equal** to the number of employees **moving in**. For example if `n = 3` and two employees are leaving building `0`, one is leaving building `1`, and one is leaving building `2`, there should be two employees moving to building `0`, one employee moving to building `1`, and one employee moving to building `2`. Return _the maximum number of achievable requests_. **Example 1:** **Input:** n = 5, requests = \[\[0,1\],\[1,0\],\[0,1\],\[1,2\],\[2,0\],\[3,4\]\] **Output:** 5 **Explantion:** Let's see the requests: From building 0 we have employees x and y and both want to move to building 1. From building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively. From building 2 we have employee z and they want to move to building 0. From building 3 we have employee c and they want to move to building 4. From building 4 we don't have any requests. We can achieve the requests of users x and b by swapping their places. We can achieve the requests of users y, a and z by swapping the places in the 3 buildings. **Example 2:** **Input:** n = 3, requests = \[\[0,0\],\[1,2\],\[2,1\]\] **Output:** 3 **Explantion:** Let's see the requests: From building 0 we have employee x and they want to stay in the same building 0. From building 1 we have employee y and they want to move to building 2. From building 2 we have employee z and they want to move to building 1. We can achieve all the requests. **Example 3:** **Input:** n = 4, requests = \[\[0,3\],\[3,1\],\[1,2\],\[2,0\]\] **Output:** 4 **Constraints:** * `1 <= n <= 20` * `1 <= requests.length <= 16` * `requests[i].length == 2` * `0 <= fromi, toi < n`
null