sol_id
stringlengths
6
6
problem_id
stringlengths
6
6
problem_text
stringlengths
322
4.55k
solution_text
stringlengths
137
5.74k
c99d1a
a9985d
You are given a 0-indexed integer array stations of length n, where stations[i] represents the number of power stations in the ith city. Each power station can provide power to every city in a fixed range. In other words, if the range is denoted by r, then a power station at city i can provide power to all cities j such that |i - j| <= r and 0 <= i, j <= n - 1. Note that |x| denotes absolute value. For example, |7 - 5| = 2 and |3 - 10| = 7. The power of a city is the total number of power stations it is being provided power from. The government has sanctioned building k more power stations, each of which can be built in any city, and have the same range as the pre-existing ones. Given the two integers r and k, return the maximum possible minimum power of a city, if the additional power stations are built optimally. Note that you can build the k power stations in multiple cities.   Example 1: Input: stations = [1,2,4,5,0], r = 1, k = 2 Output: 5 Explanation: One of the optimal ways is to install both the power stations at city 1. So stations will become [1,4,4,5,0]. - City 0 is provided by 1 + 4 = 5 power stations. - City 1 is provided by 1 + 4 + 4 = 9 power stations. - City 2 is provided by 4 + 4 + 5 = 13 power stations. - City 3 is provided by 5 + 4 = 9 power stations. - City 4 is provided by 5 + 0 = 5 power stations. So the minimum power of a city is 5. Since it is not possible to obtain a larger power, we return 5. Example 2: Input: stations = [4,4,4,4], r = 0, k = 3 Output: 4 Explanation: It can be proved that we cannot make the minimum power of a city greater than 4.   Constraints: n == stations.length 1 <= n <= 100000 0 <= stations[i] <= 100000 0 <= r <= n - 1 0 <= k <= 10^9
class Solution: def maxPower(self, a: List[int], x: int, k: int) -> int: n = len(a) dif = [0] * (n + 1) for i in range(n): dif[max(0, i - x)] += a[i] dif[min(n - 1, i + x) + 1] -= a[i] # print(dif) l, r = 0, 10 ** 18 while l <= r: mid = (l + r) // 2 d = dif[:] need = 0 cur = 0 for i in range(n): cur += d[i] if cur < mid: need += mid - cur d[i] += mid - cur d[min(n - 1, i + 2 * x) + 1] -= mid - cur cur = mid # print(mid, need, d) if need <= k: l = mid + 1 else: r = mid - 1 return r
7dff2c
a9985d
You are given a 0-indexed integer array stations of length n, where stations[i] represents the number of power stations in the ith city. Each power station can provide power to every city in a fixed range. In other words, if the range is denoted by r, then a power station at city i can provide power to all cities j such that |i - j| <= r and 0 <= i, j <= n - 1. Note that |x| denotes absolute value. For example, |7 - 5| = 2 and |3 - 10| = 7. The power of a city is the total number of power stations it is being provided power from. The government has sanctioned building k more power stations, each of which can be built in any city, and have the same range as the pre-existing ones. Given the two integers r and k, return the maximum possible minimum power of a city, if the additional power stations are built optimally. Note that you can build the k power stations in multiple cities.   Example 1: Input: stations = [1,2,4,5,0], r = 1, k = 2 Output: 5 Explanation: One of the optimal ways is to install both the power stations at city 1. So stations will become [1,4,4,5,0]. - City 0 is provided by 1 + 4 = 5 power stations. - City 1 is provided by 1 + 4 + 4 = 9 power stations. - City 2 is provided by 4 + 4 + 5 = 13 power stations. - City 3 is provided by 5 + 4 = 9 power stations. - City 4 is provided by 5 + 0 = 5 power stations. So the minimum power of a city is 5. Since it is not possible to obtain a larger power, we return 5. Example 2: Input: stations = [4,4,4,4], r = 0, k = 3 Output: 4 Explanation: It can be proved that we cannot make the minimum power of a city greater than 4.   Constraints: n == stations.length 1 <= n <= 100000 0 <= stations[i] <= 100000 0 <= r <= n - 1 0 <= k <= 10^9
class Solution(object): def maxPower(self, stations, r, k): """ :type stations: List[int] :type r: int :type k: int :rtype: int """ st=0 end=10**15 n=len(stations) while st<=end: mid=(st+end)/2 summ=0 arr=stations[:] c=0 for i in range(r): summ+=arr[i] for i in range(n): if i>r: summ-=arr[i-r-1] if i+r<n: summ+=arr[i+r] if summ<mid: x=mid-summ c+=x if i+r<n: arr[i+r]+=x else: arr[n-1]+=x summ+=x if c<=k: st=mid+1 else: end=mid-1 return end
a31214
f54fea
Special binary strings are binary strings with the following two properties: The number of 0's is equal to the number of 1's. Every prefix of the binary string has at least as many 1's as 0's. You are given a special binary string s. A move consists of choosing two consecutive, non-empty, special substrings of s, and swapping them. Two strings are consecutive if the last character of the first string is exactly one index before the first character of the second string. Return the lexicographically largest resulting string possible after applying the mentioned operations on the string.   Example 1: Input: s = "11011000" Output: "11100100" Explanation: The strings "10" [occuring at s[1]] and "1100" [at s[3]] are swapped. This is the lexicographically largest string possible after some number of swaps. Example 2: Input: s = "10" Output: "10"   Constraints: 1 <= s.length <= 50 s[i] is either '0' or '1'. s is a special binary string.
import collections class Solution(object): def makeLargestSpecial(self, S): """ :type S: str :rtype: str """ S = list(S) i = 0 while i < len(S): if S[i] == "0": # find a special substring ending in S j = i-1 count = -1 while j >= 0: if S[j] == "1": count += 1 else: count -= 1 if count == 0: break j -= 1 if count == 0: start = j end = i+1 ss = S[start:end] if end == len(S) or S[end] == "0": i += 1 continue # Find a special string starting here secs = end sece = secs+1 count = 1 while sece < len(S): count += 1 if S[sece] == "1" else -1 if count == 0: break sece += 1 if count == 0: sece += 1 second = S[secs:sece] #print(ss," and ", second) if(ss+second < second+ss): # Swap these temp = ss #print(S) #print(S[start:end] , S[secs:sece]) S = S[:start] + S[secs:sece] + S[start:end] + S[sece:] return "".join(self.makeLargestSpecial(S)) i += 1 return "".join(S)
38013f
f54fea
Special binary strings are binary strings with the following two properties: The number of 0's is equal to the number of 1's. Every prefix of the binary string has at least as many 1's as 0's. You are given a special binary string s. A move consists of choosing two consecutive, non-empty, special substrings of s, and swapping them. Two strings are consecutive if the last character of the first string is exactly one index before the first character of the second string. Return the lexicographically largest resulting string possible after applying the mentioned operations on the string.   Example 1: Input: s = "11011000" Output: "11100100" Explanation: The strings "10" [occuring at s[1]] and "1100" [at s[3]] are swapped. This is the lexicographically largest string possible after some number of swaps. Example 2: Input: s = "10" Output: "10"   Constraints: 1 <= s.length <= 50 s[i] is either '0' or '1'. s is a special binary string.
class Solution: def makeLargestSpecial(self, S): """ :type S: str :rtype: str """ # 110100 11110000 111000 # 1 10 10 0 11110000 111000 # 11101000 parts = [] p = '' ones= 0 for c in S: p += c ones += 1 if c == '1' else -1 if ones == 0: parts.append(p) p = '' if len(parts) == 1: return '1' + self.makeLargestSpecial(S[1:-1]) + '0' else: parts = [self.makeLargestSpecial(p) for p in parts] parts.sort() return ''.join(reversed(parts))
40d8dc
59b490
A conveyor belt has packages that must be shipped from one port to another within days days. The ith package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the ship. Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within days days.   Example 1: Input: weights = [1,2,3,4,5,6,7,8,9,10], days = 5 Output: 15 Explanation: A ship capacity of 15 is the minimum to ship all the packages in 5 days like this: 1st day: 1, 2, 3, 4, 5 2nd day: 6, 7 3rd day: 8 4th day: 9 5th day: 10 Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed. Example 2: Input: weights = [3,2,2,4,1,4], days = 3 Output: 6 Explanation: A ship capacity of 6 is the minimum to ship all the packages in 3 days like this: 1st day: 3, 2 2nd day: 2, 4 3rd day: 1, 4 Example 3: Input: weights = [1,2,3,1,1], days = 4 Output: 3 Explanation: 1st day: 1 2nd day: 2 3rd day: 3 4th day: 1, 1   Constraints: 1 <= days <= weights.length <= 5 * 10000 1 <= weights[i] <= 500
class Solution(object): def shipWithinDays(self, weights, D): """ :type weights: List[int] :type D: int :rtype: int """ nums = weights m = D def valid(mid): cnt = 0 current = 0 for n in nums: current += n if current>mid: cnt += 1 if cnt>=m: return False current = n return True l = max(nums) h = sum(nums) while l<h: mid = l+(h-l)/2 if valid(mid): h = mid else: l = mid+1 return l
bef0ed
59b490
A conveyor belt has packages that must be shipped from one port to another within days days. The ith package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the ship. Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within days days.   Example 1: Input: weights = [1,2,3,4,5,6,7,8,9,10], days = 5 Output: 15 Explanation: A ship capacity of 15 is the minimum to ship all the packages in 5 days like this: 1st day: 1, 2, 3, 4, 5 2nd day: 6, 7 3rd day: 8 4th day: 9 5th day: 10 Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed. Example 2: Input: weights = [3,2,2,4,1,4], days = 3 Output: 6 Explanation: A ship capacity of 6 is the minimum to ship all the packages in 3 days like this: 1st day: 3, 2 2nd day: 2, 4 3rd day: 1, 4 Example 3: Input: weights = [1,2,3,1,1], days = 4 Output: 3 Explanation: 1st day: 1 2nd day: 2 3rd day: 3 4th day: 1, 1   Constraints: 1 <= days <= weights.length <= 5 * 10000 1 <= weights[i] <= 500
class Solution: def shipWithinDays(self, weights: List[int], d: int) -> int: l = 1 r = sum(weights) res = 100000000 while l <= r: m = (l + r) // 2 t = 0 c = 1 flag = False for x in weights: if x > m: flag = True break if t + x > m: t = x c += 1 else: t += x if flag: l = m + 1 else: if c <= d: res = min(res, m) r = m - 1 else: l = m + 1 return res
2c7542
7c78a5
Given two integer arrays arr1 and arr2, return the minimum number of operations (possibly zero) needed to make arr1 strictly increasing. In one operation, you can choose two indices 0 <= i < arr1.length and 0 <= j < arr2.length and do the assignment arr1[i] = arr2[j]. If there is no way to make arr1 strictly increasing, return -1.   Example 1: Input: arr1 = [1,5,3,6,7], arr2 = [1,3,2,4] Output: 1 Explanation: Replace 5 with 2, then arr1 = [1, 2, 3, 6, 7]. Example 2: Input: arr1 = [1,5,3,6,7], arr2 = [4,3,1] Output: 2 Explanation: Replace 5 with 3 and then replace 3 with 4. arr1 = [1, 3, 4, 6, 7]. Example 3: Input: arr1 = [1,5,3,6,7], arr2 = [1,6,3,3] Output: -1 Explanation: You can't make arr1 strictly increasing.   Constraints: 1 <= arr1.length, arr2.length <= 2000 0 <= arr1[i], arr2[i] <= 10^9  
from bisect import bisect_left, bisect_right class Solution: def makeArrayIncreasing(self, arr1: List[int], arr2: List[int]) -> int: arr2.sort() dx = { -1 : 0 } for a in arr1: ndx = { } for x, d in dx.items(): if a > x: ndx[a] = min(ndx.get(a, float('inf')), d) i = bisect_right(arr2, x) if i < len(arr2): ndx[arr2[i]] = min(ndx.get(arr2[i], float('inf')), d + 1) dx = ndx return -1 if not dx else min(dx.values())
ae94ad
7c78a5
Given two integer arrays arr1 and arr2, return the minimum number of operations (possibly zero) needed to make arr1 strictly increasing. In one operation, you can choose two indices 0 <= i < arr1.length and 0 <= j < arr2.length and do the assignment arr1[i] = arr2[j]. If there is no way to make arr1 strictly increasing, return -1.   Example 1: Input: arr1 = [1,5,3,6,7], arr2 = [1,3,2,4] Output: 1 Explanation: Replace 5 with 2, then arr1 = [1, 2, 3, 6, 7]. Example 2: Input: arr1 = [1,5,3,6,7], arr2 = [4,3,1] Output: 2 Explanation: Replace 5 with 3 and then replace 3 with 4. arr1 = [1, 3, 4, 6, 7]. Example 3: Input: arr1 = [1,5,3,6,7], arr2 = [1,6,3,3] Output: -1 Explanation: You can't make arr1 strictly increasing.   Constraints: 1 <= arr1.length, arr2.length <= 2000 0 <= arr1[i], arr2[i] <= 10^9  
class Solution(object): def makeArrayIncreasing(self, arr1, arr2): """ :type arr1: List[int] :type arr2: List[int] :rtype: int """ a = arr1 s = sorted(set(arr2)) def merge(b, free_val): i = 0 m = float('inf') r = [] considered_free = False for val in s: if not considered_free and free_val <= val: while i < len(b) and b[i][0] < free_val: m = min(m, b[i][1]) i += 1 if i: r.append((free_val, m)) considered_free = True if free_val == val: continue while i < len(b) and b[i][0] < val: m = min(m, b[i][1]) i += 1 if i: r.append((val, m+1)) if not considered_free: while i < len(b) and b[i][0] < free_val: m = min(m, b[i][1]) i += 1 if i: r.append((free_val, m)) return r r = [(float('-inf'), 0)] for v in arr1: r = merge(r, v) if not r: return -1 return min(m for _, m in r)
b74de6
c9d898
You are given two integers n and maxValue, which are used to describe an ideal array. A 0-indexed integer array arr of length n is considered ideal if the following conditions hold: Every arr[i] is a value from 1 to maxValue, for 0 <= i < n. Every arr[i] is divisible by arr[i - 1], for 0 < i < n. Return the number of distinct ideal arrays of length n. Since the answer may be very large, return it modulo 10^9 + 7.   Example 1: Input: n = 2, maxValue = 5 Output: 10 Explanation: The following are the possible ideal arrays: - Arrays starting with the value 1 (5 arrays): [1,1], [1,2], [1,3], [1,4], [1,5] - Arrays starting with the value 2 (2 arrays): [2,2], [2,4] - Arrays starting with the value 3 (1 array): [3,3] - Arrays starting with the value 4 (1 array): [4,4] - Arrays starting with the value 5 (1 array): [5,5] There are a total of 5 + 2 + 1 + 1 + 1 = 10 distinct ideal arrays. Example 2: Input: n = 5, maxValue = 3 Output: 11 Explanation: The following are the possible ideal arrays: - Arrays starting with the value 1 (9 arrays): - With no other distinct values (1 array): [1,1,1,1,1] - With 2nd distinct value 2 (4 arrays): [1,1,1,1,2], [1,1,1,2,2], [1,1,2,2,2], [1,2,2,2,2] - With 2nd distinct value 3 (4 arrays): [1,1,1,1,3], [1,1,1,3,3], [1,1,3,3,3], [1,3,3,3,3] - Arrays starting with the value 2 (1 array): [2,2,2,2,2] - Arrays starting with the value 3 (1 array): [3,3,3,3,3] There are a total of 9 + 1 + 1 = 11 distinct ideal arrays.   Constraints: 2 <= n <= 10000 1 <= maxValue <= 10000
class Solution: def idealArrays(self, n: int, m: int) -> int: ans = 0 fact = [1] inv = [1] for i in range(1, n+1): fact.append(fact[-1]*i%1000000007) inv.append(pow(fact[-1], 1000000005, 1000000007)) def ncr(x, y): return fact[x]*inv[y]*inv[x-y]%1000000007 for i in range(1, 15): if i > n: continue res = [0]+[1]*m for z in range(i-1): cur = [0]*(m+1) for x in range(1, m+1): for j in range(x*2, m+1, x): cur[j] += res[x] res = [i%1000000007 for i in cur] s = sum(res)%1000000007 ans += s*ncr(n-1, i-1) return ans%1000000007
7fa6fc
c9d898
You are given two integers n and maxValue, which are used to describe an ideal array. A 0-indexed integer array arr of length n is considered ideal if the following conditions hold: Every arr[i] is a value from 1 to maxValue, for 0 <= i < n. Every arr[i] is divisible by arr[i - 1], for 0 < i < n. Return the number of distinct ideal arrays of length n. Since the answer may be very large, return it modulo 10^9 + 7.   Example 1: Input: n = 2, maxValue = 5 Output: 10 Explanation: The following are the possible ideal arrays: - Arrays starting with the value 1 (5 arrays): [1,1], [1,2], [1,3], [1,4], [1,5] - Arrays starting with the value 2 (2 arrays): [2,2], [2,4] - Arrays starting with the value 3 (1 array): [3,3] - Arrays starting with the value 4 (1 array): [4,4] - Arrays starting with the value 5 (1 array): [5,5] There are a total of 5 + 2 + 1 + 1 + 1 = 10 distinct ideal arrays. Example 2: Input: n = 5, maxValue = 3 Output: 11 Explanation: The following are the possible ideal arrays: - Arrays starting with the value 1 (9 arrays): - With no other distinct values (1 array): [1,1,1,1,1] - With 2nd distinct value 2 (4 arrays): [1,1,1,1,2], [1,1,1,2,2], [1,1,2,2,2], [1,2,2,2,2] - With 2nd distinct value 3 (4 arrays): [1,1,1,1,3], [1,1,1,3,3], [1,1,3,3,3], [1,3,3,3,3] - Arrays starting with the value 2 (1 array): [2,2,2,2,2] - Arrays starting with the value 3 (1 array): [3,3,3,3,3] There are a total of 9 + 1 + 1 = 11 distinct ideal arrays.   Constraints: 2 <= n <= 10000 1 <= maxValue <= 10000
class Solution(object): def idealArrays(self, n, maxValue): """ :type n: int :type maxValue: int :rtype: int """ mod = 1000000007 r = 1 b=1 d=1 ff = [1]*(n+1) iff = [1]*(n+1) def egcd(a, b): if b==0: return a, 1, 0 g, pa, pb = egcd(b, a%b) return g, pb, pa-pb*(a/b) for i in range(2, n+1): ff[i]=ff[i-1]*i ff[i]%=mod _, x, y = egcd(ff[i], mod) x%=mod if x<0: x+=mod iff[i]=x dp = {} def count(c, v): if c==0: return 1 if v<=1: return 0 k = (c, v) if k in dp: return dp[k] r = 0 for b in range(2, v+1): r+=count(c-1, v/b) r%=mod dp[k]=r return r while n>=d: b<<=1 if b>maxValue: break # C(n, d)*count(d) c = ff[n]*iff[d]*iff[n-d] c%=mod c*=count(d, maxValue) c%=mod r+=c r%=mod d+=1 return r
5b9e31
866bc9
There exists an undirected and initially unrooted tree with n nodes indexed from 0 to n - 1. You are given the integer n and a 2D integer array edges of length n - 1, where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. Each node has an associated price. You are given an integer array price, where price[i] is the price of the ith node. The price sum of a given path is the sum of the prices of all nodes lying on that path. The tree can be rooted at any node root of your choice. The incurred cost after choosing root is the difference between the maximum and minimum price sum amongst all paths starting at root. Return the maximum possible cost amongst all possible root choices.   Example 1: Input: n = 6, edges = [[0,1],[1,2],[1,3],[3,4],[3,5]], price = [9,8,7,6,10,5] Output: 24 Explanation: The diagram above denotes the tree after rooting it at node 2. The first part (colored in red) shows the path with the maximum price sum. The second part (colored in blue) shows the path with the minimum price sum. - The first path contains nodes [2,1,3,4]: the prices are [7,8,6,10], and the sum of the prices is 31. - The second path contains the node [2] with the price [7]. The difference between the maximum and minimum price sum is 24. It can be proved that 24 is the maximum cost. Example 2: Input: n = 3, edges = [[0,1],[1,2]], price = [1,1,1] Output: 2 Explanation: The diagram above denotes the tree after rooting it at node 0. The first part (colored in red) shows the path with the maximum price sum. The second part (colored in blue) shows the path with the minimum price sum. - The first path contains nodes [0,1,2]: the prices are [1,1,1], and the sum of the prices is 3. - The second path contains node [0] with a price [1]. The difference between the maximum and minimum price sum is 2. It can be proved that 2 is the maximum cost.   Constraints: 1 <= n <= 100000 edges.length == n - 1 0 <= ai, bi <= n - 1 edges represents a valid tree. price.length == n 1 <= price[i] <= 100000
class Solution(object): def maxOutput(self, n, edges, price): """ :type n: int :type edges: List[List[int]] :type price: List[int] :rtype: int """ t, a = [[] for _ in range(n)], [0] def d(u, p): i, e = [], [] for v in t[u]: if v != p: f = d(v, u) i.append([f[0] + price[u], v]) e.append([f[1] + price[u], v]) if not i: i.append([price[u], u]) e.append([0, u]) if len(i) == 1: a[0] = max(a[0], i[0][0] - price[u], e[0][0]) else: i.sort() for f in e: a[0] = max(a[0], f[0] + i[-2][0] - price[u] if f[1] == i[-1][1] else f[0] + i[-1][0] - price[u]) e.sort() return [i[-1][0], e[-1][0]] for e in edges: t[e[0]].append(e[1]) t[e[1]].append(e[0]) d(0, -1) return a[0]
03a08f
866bc9
There exists an undirected and initially unrooted tree with n nodes indexed from 0 to n - 1. You are given the integer n and a 2D integer array edges of length n - 1, where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. Each node has an associated price. You are given an integer array price, where price[i] is the price of the ith node. The price sum of a given path is the sum of the prices of all nodes lying on that path. The tree can be rooted at any node root of your choice. The incurred cost after choosing root is the difference between the maximum and minimum price sum amongst all paths starting at root. Return the maximum possible cost amongst all possible root choices.   Example 1: Input: n = 6, edges = [[0,1],[1,2],[1,3],[3,4],[3,5]], price = [9,8,7,6,10,5] Output: 24 Explanation: The diagram above denotes the tree after rooting it at node 2. The first part (colored in red) shows the path with the maximum price sum. The second part (colored in blue) shows the path with the minimum price sum. - The first path contains nodes [2,1,3,4]: the prices are [7,8,6,10], and the sum of the prices is 31. - The second path contains the node [2] with the price [7]. The difference between the maximum and minimum price sum is 24. It can be proved that 24 is the maximum cost. Example 2: Input: n = 3, edges = [[0,1],[1,2]], price = [1,1,1] Output: 2 Explanation: The diagram above denotes the tree after rooting it at node 0. The first part (colored in red) shows the path with the maximum price sum. The second part (colored in blue) shows the path with the minimum price sum. - The first path contains nodes [0,1,2]: the prices are [1,1,1], and the sum of the prices is 3. - The second path contains node [0] with a price [1]. The difference between the maximum and minimum price sum is 2. It can be proved that 2 is the maximum cost.   Constraints: 1 <= n <= 100000 edges.length == n - 1 0 <= ai, bi <= n - 1 edges represents a valid tree. price.length == n 1 <= price[i] <= 100000
from typing import List, Tuple, Optional from collections import defaultdict, Counter from sortedcontainers import SortedList MOD = int(1e9 + 7) INF = int(1e20) # 给你一个 n 个节点的无向无根图,节点编号为 0 到 n - 1 。给你一个整数 n 和一个长度为 n - 1 的二维整数数组 edges ,其中 edges[i] = [ai, bi] 表示树中节点 ai 和 bi 之间有一条边。 # 每个节点都有一个价值。给你一个整数数组 price ,其中 price[i] 是第 i 个节点的价值。 # 一条路径的 价值和 是这条路径上所有节点的价值之和。 # 你可以选择树中任意一个节点作为根节点 root 。选择 root 为根的 开销 是以 root 为起点的所有路径中,价值和 最大的一条路径与最小的一条路径的差值。 # 请你返回所有节点作为根节点的选择中,最大 的 开销 为多少。 from typing import Callable, Generic, List, TypeVar T = TypeVar("T") E = Callable[[int], T] """identify element of op, and answer of leaf""" Op = Callable[[T, T], T] """merge value of child node""" Composition = Callable[[T, int, int, int], T] """return value from child node to parent node""" class Solution: def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int: class Rerooting(Generic[T]): __slots__ = ("adjList", "_n", "_decrement", "_root", "_parent", "_order") def __init__(self, n: int, decrement: int = 0): """ n: 頂点数 decrement: 頂点の値を減らす量 (1-indexedなら1, 0-indexedなら0) """ self.adjList = [[] for _ in range(n)] self._n = n self._decrement = decrement self._root = None # 一番最初に根とする頂点 def addEdge(self, u: int, v: int): """ u,v 間に無向辺を張る (u->v, v->u) """ u -= self._decrement v -= self._decrement self.adjList[u].append(v) self.adjList[v].append(u) def rerooting( self, e: E["T"], op: Op["T"], composition: Composition["T"], root=0 ) -> List["T"]: """ - e: 単位元 (root) -> res mergeの単位元 例:最も遠い点までの距離を求める場合 e=0 - op: 子の値を親にマージする関数 (childRes1,childRes2) -> newRes モノイドの性質を満たす演算を定義する それが全方位木DPをする条件 例:最も遠い点までの距離を求める場合 return max(childRes1,childRes2) - composition: 頂点の値を更新する関数 (fromRes,parent,cur,direction) -> newRes direction: 0表示用cur更新parent的dp1,1表示用parent更新cur的dp2 dpをmergeする前段階で実行する演算 例:最も遠い点までの距離を求める場合 return fromRes+1 - root: 根とする頂点 <概要> 1. rootを根としてまず一度木構造をbfsで求める 多くの場合rootは任意 (0) 2. 自身の部分木のdpの値をdp1に、自身を含まない兄弟のdpの値のmergeをdp2に入れる 木構造が定まっていることからこれが効率的に求められる。 葉側からボトムアップに実行する 3. 任意の頂点を新たに根にしたとき、部分木は ①元の部分木 ②兄弟を親とした部分木 ③元の親を親とした(元の根の方向に伸びる)部分木の三つに分かれる。 ①はstep2のdp1であり、かつdp2はstep3において、②から②と③をmergeした値へと更新されているので ②も③も分かっている。 根側からトップダウンに実行する(このことが上記の更新において重要) 計算量 O(|V|) (Vは頂点数) 参照 https://qiita.com/keymoon/items/2a52f1b0fb7ef67fb89e """ # step1 root -= self._decrement assert 0 <= root < self._n self._root = root self._parent = [-1] * self._n # 親の番号を記録 self._order = [root] # bfsの訪問順を記録 深さが広義単調増加している stack = [root] while stack: cur = stack.pop() for next in self.adjList[cur]: if next == self._parent[cur]: continue self._parent[next] = cur self._order.append(next) stack.append(next) # step2 dp1 = [e(i) for i in range(self._n)] # !子树部分的dp值 dp2 = [e(i) for i in range(self._n)] # !非子树部分的dp值 for cur in self._order[::-1]: # 从下往上拓扑序dp res = e(cur) for next in self.adjList[cur]: if self._parent[cur] == next: continue dp2[next] = res res = op(res, composition(dp1[next], cur, next, 0)) # op从下往上更新dp1 res = e(cur) for next in self.adjList[cur][::-1]: if self._parent[cur] == next: continue dp2[next] = op(res, dp2[next]) res = op(res, composition(dp1[next], cur, next, 0)) dp1[cur] = res # step3 for newRoot in self._order[1:]: # 元の根に関するdp1は既に求まっている parent = self._parent[newRoot] dp2[newRoot] = composition( op(dp2[newRoot], dp2[parent]), parent, newRoot, 1 ) # op从上往下更新dp2 dp1[newRoot] = op(dp1[newRoot], dp2[newRoot]) return dp1 def e(root: int) -> int: # mergeの単位元 # 例:最も遠い点までの距離を求める場合 e=0 return 0 def op(childRes1: int, childRes2: int) -> int: # モノイドの性質を満たす演算を定義する それが全方位木DPをする条件 # 例:最も遠い点までの距離を求める場合 return max(childRes1,childRes2) return max(childRes1, childRes2) def composition(fromRes: int, parent: int, cur: int, direction: int) -> int: # dpをmergeする前段階で実行する演算 # 例:最も遠い点までの距離を求める場合 return res+1 if direction == 0: # cur -> parent return fromRes + price[cur] return fromRes + price[parent] R = Rerooting(n) for u, v in edges: R.addEdge(u, v) res = R.rerooting(e, op, composition) return max(res)
0da7d9
9b2780
Given a positive integer n, find the smallest integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive integer exists, return -1. Note that the returned integer should fit in 32-bit integer, if there is a valid answer but it does not fit in 32-bit integer, return -1.   Example 1: Input: n = 12 Output: 21 Example 2: Input: n = 21 Output: -1   Constraints: 1 <= n <= 2^31 - 1
class Solution(object): def nextGreaterElement(self, n): """ :type n: int :rtype: int """ s = list(str(n)) if s == sorted(s, reverse=True): return -1 for i in xrange(len(s)-1, 0, -1): if s[i] > s[i-1]: break if i == 0: return -1 i -= 1 for j in xrange(len(s)-1, i, -1): if s[i] < s[j]: s[i], s[j] = s[j], s[i] break m = int(''.join(s[:i+1] + sorted(s[i+1:]))) if m > 2**31-1: return -1 return m
8c755c
c50c9e
A delivery company wants to build a new service center in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new center in a position such that the sum of the euclidean distances to all customers is minimum. Given an array positions where positions[i] = [xi, yi] is the position of the ith customer on the map, return the minimum sum of the euclidean distances to all customers. In other words, you need to choose the position of the service center [xcentre, ycentre] such that the following formula is minimized: Answers within 10-5 of the actual value will be accepted.   Example 1: Input: positions = [[0,1],[1,0],[1,2],[2,1]] Output: 4.00000 Explanation: As shown, you can see that choosing [xcentre, ycentre] = [1, 1] will make the distance to each customer = 1, the sum of all distances is 4 which is the minimum possible we can achieve. Example 2: Input: positions = [[1,1],[3,3]] Output: 2.82843 Explanation: The minimum possible sum of distances = sqrt(2) + sqrt(2) = 2.82843   Constraints: 1 <= positions.length <= 50 positions[i].length == 2 0 <= xi, yi <= 100
import numpy as np from scipy.optimize import minimize class Solution: def getMinDistSum(self, positions: List[List[int]]) -> float: x0 = sum([x for x, y in positions]) / len(positions) y0 = sum([y for x, y in positions]) / len(positions) def getCost(pt): avgX, avgY = pt cost = 0 for x, y in positions: cost += ((x - avgX) ** 2 + (y - avgY) ** 2) ** 0.5 return cost res = minimize(getCost, [x0, y0]) return res.fun
17fb96
c50c9e
A delivery company wants to build a new service center in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new center in a position such that the sum of the euclidean distances to all customers is minimum. Given an array positions where positions[i] = [xi, yi] is the position of the ith customer on the map, return the minimum sum of the euclidean distances to all customers. In other words, you need to choose the position of the service center [xcentre, ycentre] such that the following formula is minimized: Answers within 10-5 of the actual value will be accepted.   Example 1: Input: positions = [[0,1],[1,0],[1,2],[2,1]] Output: 4.00000 Explanation: As shown, you can see that choosing [xcentre, ycentre] = [1, 1] will make the distance to each customer = 1, the sum of all distances is 4 which is the minimum possible we can achieve. Example 2: Input: positions = [[1,1],[3,3]] Output: 2.82843 Explanation: The minimum possible sum of distances = sqrt(2) + sqrt(2) = 2.82843   Constraints: 1 <= positions.length <= 50 positions[i].length == 2 0 <= xi, yi <= 100
class Solution(object): def getMinDistSum(self, positions): """ :type positions: List[List[int]] :rtype: float """ if len(set(map(tuple, positions)))<=1: return 0 a = [x+y*1j for x,y in positions] score = lambda p: sum(abs(p-q) for q in a) best = min(score(i) for i in a) n = len(a) p = 0 for _ in xrange(1000): best = min(best, score(p)) p = sum(q/abs(p-q) for q in a if p!=q) / sum(1/abs(p-q) for q in a if p!=q) return best
d609f3
cfbc23
Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack. Implement the FreqStack class: FreqStack() constructs an empty frequency stack. void push(int val) pushes an integer val onto the top of the stack. int pop() removes and returns the most frequent element in the stack. If there is a tie for the most frequent element, the element closest to the stack's top is removed and returned.   Example 1: Input ["FreqStack", "push", "push", "push", "push", "push", "push", "pop", "pop", "pop", "pop"] [[], [5], [7], [5], [7], [4], [5], [], [], [], []] Output [null, null, null, null, null, null, null, 5, 7, 5, 4] Explanation FreqStack freqStack = new FreqStack(); freqStack.push(5); // The stack is [5] freqStack.push(7); // The stack is [5,7] freqStack.push(5); // The stack is [5,7,5] freqStack.push(7); // The stack is [5,7,5,7] freqStack.push(4); // The stack is [5,7,5,7,4] freqStack.push(5); // The stack is [5,7,5,7,4,5] freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,5,7,4]. freqStack.pop(); // return 7, as 5 and 7 is the most frequent, but 7 is closest to the top. The stack becomes [5,7,5,4]. freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,4]. freqStack.pop(); // return 4, as 4, 5 and 7 is the most frequent, but 4 is closest to the top. The stack becomes [5,7].   Constraints: 0 <= val <= 10^9 At most 2 * 10000 calls will be made to push and pop. It is guaranteed that there will be at least one element in the stack before calling pop.
import heapq class FreqStack: def __init__(self): self.dic,self.he,self.k={},[],0 def push(self, x): """ :type x: int :rtype: void """ if x not in self.dic: self.dic[x]=1 else: self.dic[x]+=1 heapq.heappush(self.he,(-self.dic[x],self.k,-x)) self.k-=1 def pop(self): """ :rtype: int """ _,_,n=heapq.heappop(self.he) n=-n self.dic[n]-=1 if not self.dic[n]: del self.dic[n] return n # Your FreqStack object will be instantiated and called as such: # obj = FreqStack() # obj.push(x) # param_2 = obj.pop()
a078e0
cfbc23
Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack. Implement the FreqStack class: FreqStack() constructs an empty frequency stack. void push(int val) pushes an integer val onto the top of the stack. int pop() removes and returns the most frequent element in the stack. If there is a tie for the most frequent element, the element closest to the stack's top is removed and returned.   Example 1: Input ["FreqStack", "push", "push", "push", "push", "push", "push", "pop", "pop", "pop", "pop"] [[], [5], [7], [5], [7], [4], [5], [], [], [], []] Output [null, null, null, null, null, null, null, 5, 7, 5, 4] Explanation FreqStack freqStack = new FreqStack(); freqStack.push(5); // The stack is [5] freqStack.push(7); // The stack is [5,7] freqStack.push(5); // The stack is [5,7,5] freqStack.push(7); // The stack is [5,7,5,7] freqStack.push(4); // The stack is [5,7,5,7,4] freqStack.push(5); // The stack is [5,7,5,7,4,5] freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,5,7,4]. freqStack.pop(); // return 7, as 5 and 7 is the most frequent, but 7 is closest to the top. The stack becomes [5,7,5,4]. freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,4]. freqStack.pop(); // return 4, as 4, 5 and 7 is the most frequent, but 4 is closest to the top. The stack becomes [5,7].   Constraints: 0 <= val <= 10^9 At most 2 * 10000 calls will be made to push and pop. It is guaranteed that there will be at least one element in the stack before calling pop.
class FreqStack(object): def __init__(self): self.count = {} self.curLevel = 0 self.stack = [] def push(self, x): """ :type x: int :rtype: void """ if x not in self.count: self.count[x] = 0 if self.count[x] >= len(self.stack): self.stack.append([]) self.stack[self.count[x]].append(x) self.count[x] += 1 def pop(self): """ :rtype: int """ ans = self.stack[-1].pop() if not self.stack[-1]: self.stack.pop() self.count[ans] -= 1 return ans # Your FreqStack object will be instantiated and called as such: # obj = FreqStack() # obj.push(x) # param_2 = obj.pop()
d3cb34
6f14e3
Given an array of digits which is sorted in non-decreasing order. You can write numbers using each digits[i] as many times as we want. For example, if digits = ['1','3','5'], we may write numbers such as '13', '551', and '1351315'. Return the number of positive integers that can be generated that are less than or equal to a given integer n.   Example 1: Input: digits = ["1","3","5","7"], n = 100 Output: 20 Explanation: The 20 numbers that can be written are: 1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77. Example 2: Input: digits = ["1","4","9"], n = 1000000000 Output: 29523 Explanation: We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers, 81 four digit numbers, 243 five digit numbers, 729 six digit numbers, 2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers. In total, this is 29523 integers that can be written using the digits array. Example 3: Input: digits = ["7"], n = 8 Output: 1   Constraints: 1 <= digits.length <= 9 digits[i].length == 1 digits[i] is a digit from '1' to '9'. All the values in digits are unique. digits is sorted in non-decreasing order. 1 <= n <= 10^9
class Solution(object): def atMostNGivenDigitSet(self, D, N): """ :type D: List[str] :type N: int :rtype: int """ pows=[1] ns=str(N) for _ in range(len(ns)): pows.append(pows[-1]*len(D)) ans=0 # too few digits for i in range(1,len(ns)): ans+=pows[i] # do prefixes of numbers that have the correct number of digits keep=1 for i in range(len(ns)): keep=0 for d in D: if d==ns[i]: keep=1 elif d<ns[i]: # this is digit i # digits i+1,...,len(ns)-1 are still free ans+=pows[len(ns)-i-1] if keep==0: break if keep: # i.e. it's possible to get N ans+=1 return ans
be9ed5
6f14e3
Given an array of digits which is sorted in non-decreasing order. You can write numbers using each digits[i] as many times as we want. For example, if digits = ['1','3','5'], we may write numbers such as '13', '551', and '1351315'. Return the number of positive integers that can be generated that are less than or equal to a given integer n.   Example 1: Input: digits = ["1","3","5","7"], n = 100 Output: 20 Explanation: The 20 numbers that can be written are: 1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77. Example 2: Input: digits = ["1","4","9"], n = 1000000000 Output: 29523 Explanation: We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers, 81 four digit numbers, 243 five digit numbers, 729 six digit numbers, 2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers. In total, this is 29523 integers that can be written using the digits array. Example 3: Input: digits = ["7"], n = 8 Output: 1   Constraints: 1 <= digits.length <= 9 digits[i].length == 1 digits[i] is a digit from '1' to '9'. All the values in digits are unique. digits is sorted in non-decreasing order. 1 <= n <= 10^9
class Solution: def atMostNGivenDigitSet(self, D, N): """ :type D: List[str] :type N: int :rtype: int """ def NSameDigit(D, x): if x == "": return 1 else: count = 0 for d in D: if d < x[0]: count += len(D)**(len(x) - 1) elif d == x[0]: count += NSameDigit(D, x[1:]) else: break return count x = str(N) if len(D) == 0: return 0 elif len(D) == 1: count = len(x) - 1 else: count = (len(D)**len(x) - 1)//(len(D) - 1) - 1 count += NSameDigit(D, x) return count
b42781
e488bd
The beauty of a string is the difference in frequencies between the most frequent and least frequent characters. For example, the beauty of "abaacc" is 3 - 1 = 2. Given a string s, return the sum of beauty of all of its substrings.   Example 1: Input: s = "aabcb" Output: 5 Explanation: The substrings with non-zero beauty are ["aab","aabc","aabcb","abcb","bcb"], each with beauty equal to 1. Example 2: Input: s = "aabcbaa" Output: 17   Constraints: 1 <= s.length <= 500 s consists of only lowercase English letters.
class Solution: def beautySum(self, s: str) -> int: fres = [] cur = [0] * 26 fres.append(cur[:]) for i, c in enumerate(s): cur[ord(c)-ord('a')] += 1 fres.append(cur[:]) res = 0 for i in range(len(fres)): for j in range(i+1, len(fres)): fre = [x-y for x, y in zip(fres[j], fres[i]) if x-y > 0] res += max(fre) - min(fre) return res
07b008
e488bd
The beauty of a string is the difference in frequencies between the most frequent and least frequent characters. For example, the beauty of "abaacc" is 3 - 1 = 2. Given a string s, return the sum of beauty of all of its substrings.   Example 1: Input: s = "aabcb" Output: 5 Explanation: The substrings with non-zero beauty are ["aab","aabc","aabcb","abcb","bcb"], each with beauty equal to 1. Example 2: Input: s = "aabcbaa" Output: 17   Constraints: 1 <= s.length <= 500 s consists of only lowercase English letters.
from sortedcontainers import SortedList class Solution(object): def beautySum(self, s): """ :type s: str :rtype: int """ ct=0 for i in range(len(s)): arr=SortedList() d={} for j in range(i,len(s)): d[s[j]]=d.get(s[j],0)+1 if d[s[j]]==1: arr.add(1) else: pos=arr.bisect_left(d[s[j]]-1) arr.pop(pos) arr.add(d[s[j]]) ct+=arr[-1]-arr[0] return ct
6995a2
2a70d3
We run a preorder depth-first search (DFS) on the root of a binary tree. At each node in this traversal, we output D dashes (where D is the depth of this node), then we output the value of this node.  If the depth of a node is D, the depth of its immediate child is D + 1.  The depth of the root node is 0. If a node has only one child, that child is guaranteed to be the left child. Given the output traversal of this traversal, recover the tree and return its root.   Example 1: Input: traversal = "1-2--3--4-5--6--7" Output: [1,2,5,3,4,6,7] Example 2: Input: traversal = "1-2--3---4-5--6---7" Output: [1,2,5,3,null,6,null,4,null,7] Example 3: Input: traversal = "1-401--349---90--88" Output: [1,401,null,349,88,90]   Constraints: The number of nodes in the original tree is in the range [1, 1000]. 1 <= Node.val <= 10^9
import re # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def recoverFromPreorder(self, S): """ :type S: str :rtype: TreeNode """ def parse(s): for m in re.findall(r'-*\d+', s): depth = m.count('-') yield depth, int(m[depth:]) stack = [TreeNode(None)] for depth, val in parse(S): parent = stack[depth] if depth+1 >= len(stack): stack.append(None) child = stack[depth+1] = TreeNode(val) if not parent.left: parent.left = child else: parent.right = child return stack[0].left
11ec04
2a70d3
We run a preorder depth-first search (DFS) on the root of a binary tree. At each node in this traversal, we output D dashes (where D is the depth of this node), then we output the value of this node.  If the depth of a node is D, the depth of its immediate child is D + 1.  The depth of the root node is 0. If a node has only one child, that child is guaranteed to be the left child. Given the output traversal of this traversal, recover the tree and return its root.   Example 1: Input: traversal = "1-2--3--4-5--6--7" Output: [1,2,5,3,4,6,7] Example 2: Input: traversal = "1-2--3---4-5--6---7" Output: [1,2,5,3,null,6,null,4,null,7] Example 3: Input: traversal = "1-401--349---90--88" Output: [1,401,null,349,88,90]   Constraints: The number of nodes in the original tree is in the range [1, 1000]. 1 <= Node.val <= 10^9
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def recoverFromPreorder(self, S: str) -> TreeNode: lo = 0 stack = [] for match in re.finditer(r'[0-9]+', S): # print(match.start() - lo, S[match.start():match.end()]) depth = match.start() - lo val = int(S[match.start():match.end()]) lo = match.end() node = TreeNode(val) while len(stack) > depth: stack.pop() if stack: if stack[-1].left is None: stack[-1].left = node else: stack[-1].right = node stack.append(node) return stack[0]
9e26da
85d129
Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours. Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats all of them instead and will not eat any more bananas during this hour. Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return. Return the minimum integer k such that she can eat all the bananas within h hours.   Example 1: Input: piles = [3,6,7,11], h = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], h = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], h = 6 Output: 23   Constraints: 1 <= piles.length <= 10000 piles.length <= h <= 10^9 1 <= piles[i] <= 10^9
class Solution(object): def minEatingSpeed(self, piles, H): """ :type piles: List[int] :type H: int :rtype: int """ assert len(piles) <= H a = 0 b = max(piles) while a + 1 < b: c = (a + b) // 2 if sum(1+(p-1)//c for p in piles) <= H: b = c else: a = c return b
b591ba
85d129
Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours. Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats all of them instead and will not eat any more bananas during this hour. Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return. Return the minimum integer k such that she can eat all the bananas within h hours.   Example 1: Input: piles = [3,6,7,11], h = 8 Output: 4 Example 2: Input: piles = [30,11,23,4,20], h = 5 Output: 30 Example 3: Input: piles = [30,11,23,4,20], h = 6 Output: 23   Constraints: 1 <= piles.length <= 10000 piles.length <= h <= 10^9 1 <= piles[i] <= 10^9
class Solution: def minEatingSpeed(self, piles, H): """ :type piles: List[int] :type H: int :rtype: int """ def enough(speed,H,piles): time=0 for num in piles: if num%speed: time+=num//speed+1 else: time+=num//speed return time<=H lo=1 hi=max(piles) while hi>lo: m=(lo+hi)//2 if not enough(m,H,piles): lo=m+1 else: hi=m return lo
4a5c2a
5a3999
There is a country of n cities numbered from 0 to n - 1 where all the cities are connected by bi-directional roads. The roads are represented as a 2D integer array edges where edges[i] = [xi, yi, timei] denotes a road between cities xi and yi that takes timei minutes to travel. There may be multiple roads of differing travel times connecting the same two cities, but no road connects a city to itself. Each time you pass through a city, you must pay a passing fee. This is represented as a 0-indexed integer array passingFees of length n where passingFees[j] is the amount of dollars you must pay when you pass through city j. In the beginning, you are at city 0 and want to reach city n - 1 in maxTime minutes or less. The cost of your journey is the summation of passing fees for each city that you passed through at some moment of your journey (including the source and destination cities). Given maxTime, edges, and passingFees, return the minimum cost to complete your journey, or -1 if you cannot complete it within maxTime minutes.   Example 1: Input: maxTime = 30, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3] Output: 11 Explanation: The path to take is 0 -> 1 -> 2 -> 5, which takes 30 minutes and has $11 worth of passing fees. Example 2: Input: maxTime = 29, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3] Output: 48 Explanation: The path to take is 0 -> 3 -> 4 -> 5, which takes 26 minutes and has $48 worth of passing fees. You cannot take path 0 -> 1 -> 2 -> 5 since it would take too long. Example 3: Input: maxTime = 25, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3] Output: -1 Explanation: There is no way to reach city 5 from city 0 within 25 minutes.   Constraints: 1 <= maxTime <= 1000 n == passingFees.length 2 <= n <= 1000 n - 1 <= edges.length <= 1000 0 <= xi, yi <= n - 1 1 <= timei <= 1000 1 <= passingFees[j] <= 1000  The graph may contain multiple edges between two nodes. The graph does not contain self loops.
class Solution(object): def minCost(self, maxTime, edges, passingFees): """ :type maxTime: int :type edges: List[List[int]] :type passingFees: List[int] :rtype: int """ n = len(passingFees) nei = {} for a, b, c in edges: if a not in nei: nei[a]={} if b not in nei[a] or nei[a][b]>c: nei[a][b]=c if b not in nei: nei[b]={} if a not in nei[b] or nei[b][a]>c: nei[b][a]=c dp = {} inf = 0x7ffffff def dfs(i, t): if i == n-1: return passingFees[i] if t<=0: return -1 k = (i, t) if k in dp: return dp[k] r = -1 for b in nei[i]: c = nei[i][b] if t>=c: rr = dfs(b, t-c) if rr<0: continue if r<0 or r>rr: r=rr if r!=-1: r += passingFees[i] dp[k]=r return r return dfs(0, maxTime)
0c8dd0
5a3999
There is a country of n cities numbered from 0 to n - 1 where all the cities are connected by bi-directional roads. The roads are represented as a 2D integer array edges where edges[i] = [xi, yi, timei] denotes a road between cities xi and yi that takes timei minutes to travel. There may be multiple roads of differing travel times connecting the same two cities, but no road connects a city to itself. Each time you pass through a city, you must pay a passing fee. This is represented as a 0-indexed integer array passingFees of length n where passingFees[j] is the amount of dollars you must pay when you pass through city j. In the beginning, you are at city 0 and want to reach city n - 1 in maxTime minutes or less. The cost of your journey is the summation of passing fees for each city that you passed through at some moment of your journey (including the source and destination cities). Given maxTime, edges, and passingFees, return the minimum cost to complete your journey, or -1 if you cannot complete it within maxTime minutes.   Example 1: Input: maxTime = 30, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3] Output: 11 Explanation: The path to take is 0 -> 1 -> 2 -> 5, which takes 30 minutes and has $11 worth of passing fees. Example 2: Input: maxTime = 29, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3] Output: 48 Explanation: The path to take is 0 -> 3 -> 4 -> 5, which takes 26 minutes and has $48 worth of passing fees. You cannot take path 0 -> 1 -> 2 -> 5 since it would take too long. Example 3: Input: maxTime = 25, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3] Output: -1 Explanation: There is no way to reach city 5 from city 0 within 25 minutes.   Constraints: 1 <= maxTime <= 1000 n == passingFees.length 2 <= n <= 1000 n - 1 <= edges.length <= 1000 0 <= xi, yi <= n - 1 1 <= timei <= 1000 1 <= passingFees[j] <= 1000  The graph may contain multiple edges between two nodes. The graph does not contain self loops.
class Solution: def minCost(self, maxTime: int, edges: List[List[int]], fees: List[int]) -> int: @functools.lru_cache(maxsize=None) def cost(city, time): nonlocal v if time < 0: return math.inf if city == n - 1: return fees[city] ret = math.inf for d, t in nei[city]: #if d not in v: #v.add(d) if time >= t: ret = min(ret, cost(d, time - t)) #v.discard(d) return ret + fees[city] n = len(fees) nei = [[] for _ in range(n)] e = defaultdict(lambda: math.inf) for u, v, w in edges: e[(u, v)] = min(e[(u, v)], w) for (u, v), w in e.items(): nei[u].append([v, w]) nei[v].append([u, w]) v = {0} r = cost(0, maxTime) return -1 if r == math.inf else r
44c6f9
825773
There are two types of persons: The good person: The person who always tells the truth. The bad person: The person who might tell the truth and might lie. You are given a 0-indexed 2D integer array statements of size n x n that represents the statements made by n people about each other. More specifically, statements[i][j] could be one of the following: 0 which represents a statement made by person i that person j is a bad person. 1 which represents a statement made by person i that person j is a good person. 2 represents that no statement is made by person i about person j. Additionally, no person ever makes a statement about themselves. Formally, we have that statements[i][i] = 2 for all 0 <= i < n. Return the maximum number of people who can be good based on the statements made by the n people.   Example 1: Input: statements = [[2,1,2],[1,2,2],[2,0,2]] Output: 2 Explanation: Each person makes a single statement. - Person 0 states that person 1 is good. - Person 1 states that person 0 is good. - Person 2 states that person 1 is bad. Let's take person 2 as the key. - Assuming that person 2 is a good person: - Based on the statement made by person 2, person 1 is a bad person. - Now we know for sure that person 1 is bad and person 2 is good. - Based on the statement made by person 1, and since person 1 is bad, they could be: - telling the truth. There will be a contradiction in this case and this assumption is invalid. - lying. In this case, person 0 is also a bad person and lied in their statement. - Following that person 2 is a good person, there will be only one good person in the group. - Assuming that person 2 is a bad person: - Based on the statement made by person 2, and since person 2 is bad, they could be: - telling the truth. Following this scenario, person 0 and 1 are both bad as explained before. - Following that person 2 is bad but told the truth, there will be no good persons in the group. - lying. In this case person 1 is a good person. - Since person 1 is a good person, person 0 is also a good person. - Following that person 2 is bad and lied, there will be two good persons in the group. We can see that at most 2 persons are good in the best case, so we return 2. Note that there is more than one way to arrive at this conclusion. Example 2: Input: statements = [[2,0],[0,2]] Output: 1 Explanation: Each person makes a single statement. - Person 0 states that person 1 is bad. - Person 1 states that person 0 is bad. Let's take person 0 as the key. - Assuming that person 0 is a good person: - Based on the statement made by person 0, person 1 is a bad person and was lying. - Following that person 0 is a good person, there will be only one good person in the group. - Assuming that person 0 is a bad person: - Based on the statement made by person 0, and since person 0 is bad, they could be: - telling the truth. Following this scenario, person 0 and 1 are both bad. - Following that person 0 is bad but told the truth, there will be no good persons in the group. - lying. In this case person 1 is a good person. - Following that person 0 is bad and lied, there will be only one good person in the group. We can see that at most, one person is good in the best case, so we return 1. Note that there is more than one way to arrive at this conclusion.   Constraints: n == statements.length == statements[i].length 2 <= n <= 15 statements[i][j] is either 0, 1, or 2. statements[i][i] == 2
class Solution(object): def maximumGood(self, statements): """ :type statements: List[List[int]] :rtype: int """ a = statements n = len(a) m = 1<<n pc = [0]*m for i in xrange(1, m): pc[i] = pc[i&(i-1)]+1 def _check(msk): t = [(msk>>i)&1 for i in xrange(n)] for i in xrange(n): if not t[i]: # not trustworthy continue for j in xrange(n): if a[i][j] != 2 and t[j] != a[i][j]: return False return True return max(pc[msk] for msk in xrange(m) if _check(msk))
749a1c
825773
There are two types of persons: The good person: The person who always tells the truth. The bad person: The person who might tell the truth and might lie. You are given a 0-indexed 2D integer array statements of size n x n that represents the statements made by n people about each other. More specifically, statements[i][j] could be one of the following: 0 which represents a statement made by person i that person j is a bad person. 1 which represents a statement made by person i that person j is a good person. 2 represents that no statement is made by person i about person j. Additionally, no person ever makes a statement about themselves. Formally, we have that statements[i][i] = 2 for all 0 <= i < n. Return the maximum number of people who can be good based on the statements made by the n people.   Example 1: Input: statements = [[2,1,2],[1,2,2],[2,0,2]] Output: 2 Explanation: Each person makes a single statement. - Person 0 states that person 1 is good. - Person 1 states that person 0 is good. - Person 2 states that person 1 is bad. Let's take person 2 as the key. - Assuming that person 2 is a good person: - Based on the statement made by person 2, person 1 is a bad person. - Now we know for sure that person 1 is bad and person 2 is good. - Based on the statement made by person 1, and since person 1 is bad, they could be: - telling the truth. There will be a contradiction in this case and this assumption is invalid. - lying. In this case, person 0 is also a bad person and lied in their statement. - Following that person 2 is a good person, there will be only one good person in the group. - Assuming that person 2 is a bad person: - Based on the statement made by person 2, and since person 2 is bad, they could be: - telling the truth. Following this scenario, person 0 and 1 are both bad as explained before. - Following that person 2 is bad but told the truth, there will be no good persons in the group. - lying. In this case person 1 is a good person. - Since person 1 is a good person, person 0 is also a good person. - Following that person 2 is bad and lied, there will be two good persons in the group. We can see that at most 2 persons are good in the best case, so we return 2. Note that there is more than one way to arrive at this conclusion. Example 2: Input: statements = [[2,0],[0,2]] Output: 1 Explanation: Each person makes a single statement. - Person 0 states that person 1 is bad. - Person 1 states that person 0 is bad. Let's take person 0 as the key. - Assuming that person 0 is a good person: - Based on the statement made by person 0, person 1 is a bad person and was lying. - Following that person 0 is a good person, there will be only one good person in the group. - Assuming that person 0 is a bad person: - Based on the statement made by person 0, and since person 0 is bad, they could be: - telling the truth. Following this scenario, person 0 and 1 are both bad. - Following that person 0 is bad but told the truth, there will be no good persons in the group. - lying. In this case person 1 is a good person. - Following that person 0 is bad and lied, there will be only one good person in the group. We can see that at most, one person is good in the best case, so we return 1. Note that there is more than one way to arrive at this conclusion.   Constraints: n == statements.length == statements[i].length 2 <= n <= 15 statements[i][j] is either 0, 1, or 2. statements[i][i] == 2
class Solution: def maximumGood(self, statements: List[List[int]]) -> int: def popcount(mask): ans = 0 while mask: ans += mask % 2 mask >>= 1 return ans n = len(statements) def check(mask): for i in range(n): good = bool(mask >> i & 1) if not good: continue for j in range(n): if statements[i][j] == 2: continue good2 = bool(mask >> j & 1) state = statements[i][j] == 1 if good2 != state: return False return True ans = 0 for mask in range(1 << n): if check(mask): ans = max(ans, popcount(mask)) return ans
d159ff
d4280b
You are given a string s containing lowercase letters and an integer k. You need to : First, change some characters of s to other lowercase English letters. Then divide s into k non-empty disjoint substrings such that each substring is a palindrome. Return the minimal number of characters that you need to change to divide the string.   Example 1: Input: s = "abc", k = 2 Output: 1 Explanation: You can split the string into "ab" and "c", and change 1 character in "ab" to make it palindrome. Example 2: Input: s = "aabbc", k = 3 Output: 0 Explanation: You can split the string into "aa", "bb" and "c", all of them are palindrome. Example 3: Input: s = "leetcode", k = 8 Output: 0   Constraints: 1 <= k <= s.length <= 100. s only contains lowercase English letters.
class Solution(object): def palindromePartition(self, S, K): # Min changes so you can make S split into K palindromes def memoize(f): class memodict(dict): def __init__(self, f): self.f = f def __call__(self, *args): return self[args] def __missing__(self, key): ret = self[key] = self.f(*key) return ret return memodict(f) @memoize def topali(i, j): if i == j: return 0 if i + 1 == j: if S[i] == S[j]: return 0 return 1 if S[i] == S[j]: return topali(i+1, j-1) return 1 + topali(i+1, j-1) @memoize def dp(i, k): # dp[i][k] = min changes to split S[..i] into k palindromes if k == 1: return topali(0, i) ans = i+1 for i0 in xrange(1, i + 1): cand = dp(i0 - 1, k-1) + topali(i0, i) if cand < ans: ans = cand return ans return dp(len(S) - 1, K)
85d7b1
d4280b
You are given a string s containing lowercase letters and an integer k. You need to : First, change some characters of s to other lowercase English letters. Then divide s into k non-empty disjoint substrings such that each substring is a palindrome. Return the minimal number of characters that you need to change to divide the string.   Example 1: Input: s = "abc", k = 2 Output: 1 Explanation: You can split the string into "ab" and "c", and change 1 character in "ab" to make it palindrome. Example 2: Input: s = "aabbc", k = 3 Output: 0 Explanation: You can split the string into "aa", "bb" and "c", all of them are palindrome. Example 3: Input: s = "leetcode", k = 8 Output: 0   Constraints: 1 <= k <= s.length <= 100. s only contains lowercase English letters.
class Solution: def palindromePartition(self, s: str, k: int) -> int: d = [[0]*len(s) for _ in range(len(s))] for lmid in range(len(s)): for rmid in [lmid, lmid+1]: for move in range(len(s)): l = lmid - move r = rmid + move if l<0 or r >= len(s): break if move == 0: if l == r: d[l][r] = 0 else: d[l][r] = 0 if s[l] == s[r] else 1 else: d[l][r] = d[l+1][r-1] d[l][r] += 0 if s[l] == s[r] else 1 f = [[-1]*(k+1) for _ in range(len(s))] for j in range(k): for i in range(len(s)): if j > i: continue if j == 0: f[i][j] = d[0][i] for r in range(i+1, len(s)): if f[r][j+1] == -1 or f[r][j+1] > f[i][j] + d[i+1][r]: f[r][j+1] = f[i][j] + d[i+1][r] return f[len(s)-1][k-1]
9bae00
48a812
You are given a 0-indexed binary string s which represents a sequence of train cars. s[i] = '0' denotes that the ith car does not contain illegal goods and s[i] = '1' denotes that the ith car does contain illegal goods. As the train conductor, you would like to get rid of all the cars containing illegal goods. You can do any of the following three operations any number of times: Remove a train car from the left end (i.e., remove s[0]) which takes 1 unit of time. Remove a train car from the right end (i.e., remove s[s.length - 1]) which takes 1 unit of time. Remove a train car from anywhere in the sequence which takes 2 units of time. Return the minimum time to remove all the cars containing illegal goods. Note that an empty sequence of cars is considered to have no cars containing illegal goods.   Example 1: Input: s = "1100101" Output: 5 Explanation: One way to remove all the cars containing illegal goods from the sequence is to - remove a car from the left end 2 times. Time taken is 2 * 1 = 2. - remove a car from the right end. Time taken is 1. - remove the car containing illegal goods found in the middle. Time taken is 2. This obtains a total time of 2 + 1 + 2 = 5. An alternative way is to - remove a car from the left end 2 times. Time taken is 2 * 1 = 2. - remove a car from the right end 3 times. Time taken is 3 * 1 = 3. This also obtains a total time of 2 + 3 = 5. 5 is the minimum time taken to remove all the cars containing illegal goods. There are no other ways to remove them with less time. Example 2: Input: s = "0010" Output: 2 Explanation: One way to remove all the cars containing illegal goods from the sequence is to - remove a car from the left end 3 times. Time taken is 3 * 1 = 3. This obtains a total time of 3. Another way to remove all the cars containing illegal goods from the sequence is to - remove the car containing illegal goods found in the middle. Time taken is 2. This obtains a total time of 2. Another way to remove all the cars containing illegal goods from the sequence is to - remove a car from the right end 2 times. Time taken is 2 * 1 = 2. This obtains a total time of 2. 2 is the minimum time taken to remove all the cars containing illegal goods. There are no other ways to remove them with less time.   Constraints: 1 <= s.length <= 2 * 100000 s[i] is either '0' or '1'.
class Solution: def minimumTime(self, s: str) -> int: f = 0 z = len(s) for i in range(len(s)): if s[i] == '1': f = min(i + 1, f + 2) z = min(z, f + len(s) - i - 1) return z
8ea937
48a812
You are given a 0-indexed binary string s which represents a sequence of train cars. s[i] = '0' denotes that the ith car does not contain illegal goods and s[i] = '1' denotes that the ith car does contain illegal goods. As the train conductor, you would like to get rid of all the cars containing illegal goods. You can do any of the following three operations any number of times: Remove a train car from the left end (i.e., remove s[0]) which takes 1 unit of time. Remove a train car from the right end (i.e., remove s[s.length - 1]) which takes 1 unit of time. Remove a train car from anywhere in the sequence which takes 2 units of time. Return the minimum time to remove all the cars containing illegal goods. Note that an empty sequence of cars is considered to have no cars containing illegal goods.   Example 1: Input: s = "1100101" Output: 5 Explanation: One way to remove all the cars containing illegal goods from the sequence is to - remove a car from the left end 2 times. Time taken is 2 * 1 = 2. - remove a car from the right end. Time taken is 1. - remove the car containing illegal goods found in the middle. Time taken is 2. This obtains a total time of 2 + 1 + 2 = 5. An alternative way is to - remove a car from the left end 2 times. Time taken is 2 * 1 = 2. - remove a car from the right end 3 times. Time taken is 3 * 1 = 3. This also obtains a total time of 2 + 3 = 5. 5 is the minimum time taken to remove all the cars containing illegal goods. There are no other ways to remove them with less time. Example 2: Input: s = "0010" Output: 2 Explanation: One way to remove all the cars containing illegal goods from the sequence is to - remove a car from the left end 3 times. Time taken is 3 * 1 = 3. This obtains a total time of 3. Another way to remove all the cars containing illegal goods from the sequence is to - remove the car containing illegal goods found in the middle. Time taken is 2. This obtains a total time of 2. Another way to remove all the cars containing illegal goods from the sequence is to - remove a car from the right end 2 times. Time taken is 2 * 1 = 2. This obtains a total time of 2. 2 is the minimum time taken to remove all the cars containing illegal goods. There are no other ways to remove them with less time.   Constraints: 1 <= s.length <= 2 * 100000 s[i] is either '0' or '1'.
class Solution(object): def minimumTime(self, s): """ :type s: str :rtype: int """ r, c, t, u, v, m, w, x = [0] * len(s), [0] * len(s), len(s), 1, 0, 3 * len(s), 0, len(s) - 1 for i in range(len(s) - 1, -1, -1): u = u - 1 + (2 if s[i] == '1' else 0) r[i] = u for i in range(len(s)): v += ord(s[i]) - ord('0') c[i] = v for i in range(len(s)): if r[i] < m: m, w = r[i], i t, x = min(t, w + x + (c[i] - (0 if w == 0 else c[w - 1])) * 2), x - 1 return t
2f900e
92f541
On a campus represented as a 2D grid, there are n workers and m bikes, with n <= m. Each worker and bike is a 2D coordinate on this grid. We assign one unique bike to each worker so that the sum of the Manhattan distances between each worker and their assigned bike is minimized. Return the minimum possible sum of Manhattan distances between each worker and their assigned bike. The Manhattan distance between two points p1 and p2 is Manhattan(p1, p2) = |p1.x - p2.x| + |p1.y - p2.y|. Example 1: Input: workers = [[0,0],[2,1]], bikes = [[1,2],[3,3]] Output: 6 Explanation: We assign bike 0 to worker 0, bike 1 to worker 1. The Manhattan distance of both assignments is 3, so the output is 6. Example 2: Input: workers = [[0,0],[1,1],[2,0]], bikes = [[1,0],[2,2],[2,1]] Output: 4 Explanation: We first assign bike 0 to worker 0, then assign bike 1 to worker 1 or worker 2, bike 2 to worker 2 or worker 1. Both assignments lead to sum of the Manhattan distances as 4. Example 3: Input: workers = [[0,0],[1,0],[2,0],[3,0],[4,0]], bikes = [[0,999],[1,999],[2,999],[3,999],[4,999]] Output: 4995 Constraints: n == workers.length m == bikes.length 1 <= n <= m <= 10 workers[i].length == 2 bikes[i].length == 2 0 <= workers[i][0], workers[i][1], bikes[i][0], bikes[i][1] < 1000 All the workers and the bikes locations are unique.
class Solution: def assignBikes(self, workers: List[List[int]], bikes: List[List[int]]) -> int: def get_dist(w, b): return abs(w[0] - b[0]) + abs(w[1] - b[1]) def count_bits(x): ans = 0 while x: ans += x & 1 x >>= 1 return ans M, N = len(workers), len(bikes) W = 1 << N dp = [[0] * W for _ in range(M + 1)] cnt_bits = [count_bits(j) for j in range(W)] dist = [[get_dist(workers[i], bikes[j]) for j in range(N)] for i in range(M)] # First i workers for i in range(1, M + 1): # Bikes for j in range(W): if cnt_bits[j] < i: continue dp[i][j] = float('inf') idx, cur = 0, 1 while cur <= j: if cur & j: dp[i][j] = min(dp[i][j], dp[i - 1][j - cur] + dist[i - 1][idx]) idx += 1 cur <<= 1 return dp[M][W - 1]
dc290d
92f541
On a campus represented as a 2D grid, there are n workers and m bikes, with n <= m. Each worker and bike is a 2D coordinate on this grid. We assign one unique bike to each worker so that the sum of the Manhattan distances between each worker and their assigned bike is minimized. Return the minimum possible sum of Manhattan distances between each worker and their assigned bike. The Manhattan distance between two points p1 and p2 is Manhattan(p1, p2) = |p1.x - p2.x| + |p1.y - p2.y|. Example 1: Input: workers = [[0,0],[2,1]], bikes = [[1,2],[3,3]] Output: 6 Explanation: We assign bike 0 to worker 0, bike 1 to worker 1. The Manhattan distance of both assignments is 3, so the output is 6. Example 2: Input: workers = [[0,0],[1,1],[2,0]], bikes = [[1,0],[2,2],[2,1]] Output: 4 Explanation: We first assign bike 0 to worker 0, then assign bike 1 to worker 1 or worker 2, bike 2 to worker 2 or worker 1. Both assignments lead to sum of the Manhattan distances as 4. Example 3: Input: workers = [[0,0],[1,0],[2,0],[3,0],[4,0]], bikes = [[0,999],[1,999],[2,999],[3,999],[4,999]] Output: 4995 Constraints: n == workers.length m == bikes.length 1 <= n <= m <= 10 workers[i].length == 2 bikes[i].length == 2 0 <= workers[i][0], workers[i][1], bikes[i][0], bikes[i][1] < 1000 All the workers and the bikes locations are unique.
class Solution(object): def assignBikes(self, workers, bikes): """ :type workers: List[List[int]] :type bikes: List[List[int]] :rtype: int """ n, m = len(workers), len(bikes) seen = set() def dis(i, j): return abs(workers[i][0] - bikes[j][0]) + abs(workers[i][1] - bikes[j][1]) def run(): res = random.sample(range(m), n) good = 0 while not good: good = 1 rest = set(range(m)) - set(res) for i, j1 in enumerate(res): for j2 in rest: if dis(i, j1) > dis(i, j2): res[i] = j2 good = 0 break if not good: break if not good: continue for i1, j1 in enumerate(res): for i2, j2 in enumerate(res): if dis(i1, j1) + dis(i2, j2) > dis(i1, j2) + dis(i2, j1): good = 0 res[i1], res[i2] = j2, j1 break if not good: break seen.add(sum(dis(i, j) for i, j in enumerate(res))) for _ in xrange(20): run() return min(seen)
003080
052a39
You are given an integer array nums. The value of this array is defined as the sum of |nums[i] - nums[i + 1]| for all 0 <= i < nums.length - 1. You are allowed to select any subarray of the given array and reverse it. You can perform this operation only once. Find maximum possible value of the final array.   Example 1: Input: nums = [2,3,1,5,4] Output: 10 Explanation: By reversing the subarray [3,1,5] the array becomes [2,5,1,3,4] whose value is 10. Example 2: Input: nums = [2,4,9,24,2,1,10] Output: 68   Constraints: 1 <= nums.length <= 3 * 10000 -100000 <= nums[i] <= 100000
class Solution(object): def maxValueAfterReverse(self, A): N = len(A) deltas = [abs(A[i+1] - A[i]) for i in xrange(N-1)] ans = base = sum(deltas) if N == 1: return ans a,b = A[:2] d = deltas[0] bests = [-a-b-d, -a+b-d, +a-b-d, +a+b-d] # for l = 1 for r in xrange(1, N-1): a, b = A[r], A[r+1] d = deltas[r] row = [+a+b-d, +a-b-d, -a+b-d, -a-b-d] for r0 in xrange(4): cand = base + row[r0] + bests[r0] if cand > ans: #print ('bests', bests) #print ('cand', base, ';', A, cand, r, r0) ans = cand row2 = [-a-b-d, -a+b-d, +a-b-d, +a+b-d] for r0 in xrange(4): if row2[r0] > bests[r0]: bests[r0] = row2[r0] # single moves for i in xrange(N - 1): # flip with A[0] cand = base + abs(A[i+1] - A[0]) - abs(A[i] - A[i+1]) if cand > ans: ans = cand for i in range(1, N): cand = base + abs(A[-1] - A[i-1]) - abs(A[i] - A[i-1]) if cand > ans: ans = cand return ans
3720cf
052a39
You are given an integer array nums. The value of this array is defined as the sum of |nums[i] - nums[i + 1]| for all 0 <= i < nums.length - 1. You are allowed to select any subarray of the given array and reverse it. You can perform this operation only once. Find maximum possible value of the final array.   Example 1: Input: nums = [2,3,1,5,4] Output: 10 Explanation: By reversing the subarray [3,1,5] the array becomes [2,5,1,3,4] whose value is 10. Example 2: Input: nums = [2,4,9,24,2,1,10] Output: 68   Constraints: 1 <= nums.length <= 3 * 10000 -100000 <= nums[i] <= 100000
class Solution: def maxValueAfterReverse(self, nums: List[int]) -> int: n=len(nums) if n==1: return 0 if n==2: return abs(nums[0]-nums[1]) orig=sum([abs(nums[i]-nums[i+1]) for i in range(n-1)]) M1=max([abs(nums[i]-nums[-1])-abs(nums[i]-nums[i+1]) for i in range(n-2)]) M2=max([abs(nums[i]-nums[0])-abs(nums[i]-nums[i-1]) for i in range(2,n)]) L=[sorted([nums[i],nums[i+1]]) for i in range(n-1)] m=min([x[1] for x in L]) M=max([x[0] for x in L]) if M<=m: M3=0 else: M3=2*(M-m) return orig+max(M1,M2,M3)
7a0865
9011f2
You are given two strings, word1 and word2. You want to construct a string in the following manner: Choose some non-empty subsequence subsequence1 from word1. Choose some non-empty subsequence subsequence2 from word2. Concatenate the subsequences: subsequence1 + subsequence2, to make the string. Return the length of the longest palindrome that can be constructed in the described manner. If no palindromes can be constructed, return 0. A subsequence of a string s is a string that can be made by deleting some (possibly none) characters from s without changing the order of the remaining characters. A palindrome is a string that reads the same forward as well as backward.   Example 1: Input: word1 = "cacb", word2 = "cbba" Output: 5 Explanation: Choose "ab" from word1 and "cba" from word2 to make "abcba", which is a palindrome. Example 2: Input: word1 = "ab", word2 = "ab" Output: 3 Explanation: Choose "ab" from word1 and "a" from word2 to make "aba", which is a palindrome. Example 3: Input: word1 = "aa", word2 = "bb" Output: 0 Explanation: You cannot construct a palindrome from the described method, so return 0.   Constraints: 1 <= word1.length, word2.length <= 1000 word1 and word2 consist of lowercase English letters.
from typing import * from functools import lru_cache import bisect from queue import Queue import math class Solution: def longestPalindrome(self, word1: str, word2: str) -> int: n1, n2 = len(word1), len(word2) n = n1 + n2 word = word1 + word2 @lru_cache(None) def helper(left, right, flag1, flag2): if right < n1 and not flag2: return -10**5 if left >= n1 and not flag1: return -10**5 if left == right: return 1 if left > right: return 0 if word[left] == word[right]: flag1 = flag1 or (left < n1) flag2 = flag2 or (right >= n1) return 2 + helper(left + 1, right - 1, flag1, flag2) else: return max(helper(left, right-1, flag1, flag2), helper(left+1, right, flag1, flag2)) res = helper(0, n-1,False, False) helper.cache_clear() return max(0, res)
438126
9011f2
You are given two strings, word1 and word2. You want to construct a string in the following manner: Choose some non-empty subsequence subsequence1 from word1. Choose some non-empty subsequence subsequence2 from word2. Concatenate the subsequences: subsequence1 + subsequence2, to make the string. Return the length of the longest palindrome that can be constructed in the described manner. If no palindromes can be constructed, return 0. A subsequence of a string s is a string that can be made by deleting some (possibly none) characters from s without changing the order of the remaining characters. A palindrome is a string that reads the same forward as well as backward.   Example 1: Input: word1 = "cacb", word2 = "cbba" Output: 5 Explanation: Choose "ab" from word1 and "cba" from word2 to make "abcba", which is a palindrome. Example 2: Input: word1 = "ab", word2 = "ab" Output: 3 Explanation: Choose "ab" from word1 and "a" from word2 to make "aba", which is a palindrome. Example 3: Input: word1 = "aa", word2 = "bb" Output: 0 Explanation: You cannot construct a palindrome from the described method, so return 0.   Constraints: 1 <= word1.length, word2.length <= 1000 word1 and word2 consist of lowercase English letters.
class Solution(object): def longestPalindrome(self, word1, word2): """ :type word1: str :type word2: str :rtype: int """ n1, n2 = len(word1), len(word2) s = word1 + word2 n = len(s) f = [[0]*n for _ in xrange(n)] for i in xrange(n): f[i][i] = 1 for l in xrange(2, 1+n): for i in xrange(1+n-l): j = i + l - 1 f[i][j] = max(f[i][j-1], f[i+1][j]) if s[i] == s[j]: f[i][j] = max(f[i][j], 2 + f[i+1][j-1]) best = 0 for i in xrange(n1): for j in xrange(n1, n): if s[i] == s[j]: best = max(best, 2 + f[i+1][j-1]) return best
2c7d58
068bbd
Given an integer array arr and an integer k, modify the array by repeating it k times. For example, if arr = [1, 2] and k = 3 then the modified array will be [1, 2, 1, 2, 1, 2]. Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be 0 and its sum in that case is 0. As the answer can be very large, return the answer modulo 10^9 + 7.   Example 1: Input: arr = [1,2], k = 3 Output: 9 Example 2: Input: arr = [1,-2,1], k = 5 Output: 2 Example 3: Input: arr = [-1,-2], k = 7 Output: 0   Constraints: 1 <= arr.length <= 100000 1 <= k <= 100000 -10000 <= arr[i] <= 10000
class Solution: def kConcatenationMaxSum(self, arr: List[int], k: int) -> int: cur=arr[0] prefix_max=cur for num in arr[1:]: cur+=num prefix_max=max(prefix_max,cur) prefix_max=max(0,prefix_max) total_sum=cur cur=arr[-1] suffix_max=max(cur,0) for num in reversed(arr[:-1]): cur+=num suffix_max=max(suffix_max,cur) def helper(arr): ans=cur=arr[0] for num in arr[1:]: if cur>0: cur=num+cur else: cur=num ans=max(ans,cur) return ans ans=0 if k==1: ans=max(ans,helper(arr)) elif k==2: ans=max(ans,helper(arr+arr)) else: ans=max(ans,helper(arr)) ans=max(ans,helper(arr+arr)) ans=max(ans,prefix_max+suffix_max+(k-2)*max(0,total_sum)) return ans%(10**9+7)
b25f53
068bbd
Given an integer array arr and an integer k, modify the array by repeating it k times. For example, if arr = [1, 2] and k = 3 then the modified array will be [1, 2, 1, 2, 1, 2]. Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be 0 and its sum in that case is 0. As the answer can be very large, return the answer modulo 10^9 + 7.   Example 1: Input: arr = [1,2], k = 3 Output: 9 Example 2: Input: arr = [1,-2,1], k = 5 Output: 2 Example 3: Input: arr = [-1,-2], k = 7 Output: 0   Constraints: 1 <= arr.length <= 100000 1 <= k <= 100000 -10000 <= arr[i] <= 10000
class Solution(object): def kConcatenationMaxSum(self, A, K): def kadane(A): ans = bns = 0 for x in A: bns += x if x > bns: bns = x if bns > ans: ans = bns return ans MOD = 10**9 + 7 N = len(A) if K <= 2: return kadane(A) %MOD if K == 1 else kadane(A+A) %MOD S = sum(A) if S <= 0: return max(kadane(A), kadane(A+A)) % MOD base = S * (K-2) % MOD prefix = suffix = 0 su = 0 for x in A: su += x if su > prefix: prefix = su su = 0 for x in reversed(A): su += x if su > suffix: suffix = su return (base + prefix + suffix) % MOD
fd4177
abfaf2
Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise. In other words, return true if one of s1's permutations is the substring of s2.   Example 1: Input: s1 = "ab", s2 = "eidbaooo" Output: true Explanation: s2 contains one permutation of s1 ("ba"). Example 2: Input: s1 = "ab", s2 = "eidboaoo" Output: false   Constraints: 1 <= s1.length, s2.length <= 10000 s1 and s2 consist of lowercase English letters.
class Solution(object): def checkInclusion(self, s1, s2): """ :type s1: str :type s2: str :rtype: bool """ s = 0 l = len(s1) if l == 0: return True for c in s1: s += 1 << (ord(c) - 97) su = 0 ss = [0] * (len(s2) + 1) for i in range(len(s2)): su += 1 << (ord(s2[i]) - 97) ss[i + 1] = su if i + 1 - l >= 0 and su - ss[i + 1 - l] == s: return True return False
85c0e6
d31e8d
There is a survey that consists of n questions where each question's answer is either 0 (no) or 1 (yes). The survey was given to m students numbered from 0 to m - 1 and m mentors numbered from 0 to m - 1. The answers of the students are represented by a 2D integer array students where students[i] is an integer array that contains the answers of the ith student (0-indexed). The answers of the mentors are represented by a 2D integer array mentors where mentors[j] is an integer array that contains the answers of the jth mentor (0-indexed). Each student will be assigned to one mentor, and each mentor will have one student assigned to them. The compatibility score of a student-mentor pair is the number of answers that are the same for both the student and the mentor. For example, if the student's answers were [1, 0, 1] and the mentor's answers were [0, 0, 1], then their compatibility score is 2 because only the second and the third answers are the same. You are tasked with finding the optimal student-mentor pairings to maximize the sum of the compatibility scores. Given students and mentors, return the maximum compatibility score sum that can be achieved.   Example 1: Input: students = [[1,1,0],[1,0,1],[0,0,1]], mentors = [[1,0,0],[0,0,1],[1,1,0]] Output: 8 Explanation: We assign students to mentors in the following way: - student 0 to mentor 2 with a compatibility score of 3. - student 1 to mentor 0 with a compatibility score of 2. - student 2 to mentor 1 with a compatibility score of 3. The compatibility score sum is 3 + 2 + 3 = 8. Example 2: Input: students = [[0,0],[0,0],[0,0]], mentors = [[1,1],[1,1],[1,1]] Output: 0 Explanation: The compatibility score of any student-mentor pair is 0.   Constraints: m == students.length == mentors.length n == students[i].length == mentors[j].length 1 <= m, n <= 8 students[i][k] is either 0 or 1. mentors[j][k] is either 0 or 1.
class Solution(object): def maxCompatibilitySum(self, students, mentors): """ :type students: List[List[int]] :type mentors: List[List[int]] :rtype: int """ a, b = students, mentors m, n = len(a), len(a[0]) s = [[n-sum(a[i][k]^b[j][k] for k in xrange(n)) for j in xrange(m)] for i in xrange(m)] t = 1 << m f = {0: 0} for score in s: ff = Counter() for k, v in f.iteritems(): for j in xrange(m): kk = k | (1 << j) if kk > k: ff[kk] = max(ff[kk], v + score[j]) f = ff return max(f.itervalues())
00d9db
d31e8d
There is a survey that consists of n questions where each question's answer is either 0 (no) or 1 (yes). The survey was given to m students numbered from 0 to m - 1 and m mentors numbered from 0 to m - 1. The answers of the students are represented by a 2D integer array students where students[i] is an integer array that contains the answers of the ith student (0-indexed). The answers of the mentors are represented by a 2D integer array mentors where mentors[j] is an integer array that contains the answers of the jth mentor (0-indexed). Each student will be assigned to one mentor, and each mentor will have one student assigned to them. The compatibility score of a student-mentor pair is the number of answers that are the same for both the student and the mentor. For example, if the student's answers were [1, 0, 1] and the mentor's answers were [0, 0, 1], then their compatibility score is 2 because only the second and the third answers are the same. You are tasked with finding the optimal student-mentor pairings to maximize the sum of the compatibility scores. Given students and mentors, return the maximum compatibility score sum that can be achieved.   Example 1: Input: students = [[1,1,0],[1,0,1],[0,0,1]], mentors = [[1,0,0],[0,0,1],[1,1,0]] Output: 8 Explanation: We assign students to mentors in the following way: - student 0 to mentor 2 with a compatibility score of 3. - student 1 to mentor 0 with a compatibility score of 2. - student 2 to mentor 1 with a compatibility score of 3. The compatibility score sum is 3 + 2 + 3 = 8. Example 2: Input: students = [[0,0],[0,0],[0,0]], mentors = [[1,1],[1,1],[1,1]] Output: 0 Explanation: The compatibility score of any student-mentor pair is 0.   Constraints: m == students.length == mentors.length n == students[i].length == mentors[j].length 1 <= m, n <= 8 students[i][k] is either 0 or 1. mentors[j][k] is either 0 or 1.
import operator import functools class Solution: def maxCompatibilitySum(self, students: List[List[int]], mentors: List[List[int]]) -> int: n = len(students[0]) m = len(students) score_table = [] for i in range(m): score_table.append([None] * m) for i in range(m): for j in range(m): score_table[i][j] = sum(map(operator.eq, students[i], mentors[j])) @functools.lru_cache(50000) def assign(stu, ava): if stu == m: assert not any(ava) return 0 ans = 0 a = list(ava) for index, i in enumerate(ava): if i: a[index] = False ans = max(assign(stu + 1, tuple(a)) + score_table[stu][index], ans) a[index] = True return ans # print(score_table) answer = assign(0, (True,) * m) return answer
a5af80
88ae4e
The hash of a 0-indexed string s of length k, given integers p and m, is computed using the following function: hash(s, p, m) = (val(s[0]) * p0 + val(s[1]) * p1 + ... + val(s[k-1]) * pk-1) mod m. Where val(s[i]) represents the index of s[i] in the alphabet from val('a') = 1 to val('z') = 26. You are given a string s and the integers power, modulo, k, and hashValue. Return sub, the first substring of s of length k such that hash(sub, power, modulo) == hashValue. The test cases will be generated such that an answer always exists. A substring is a contiguous non-empty sequence of characters within a string.   Example 1: Input: s = "leetcode", power = 7, modulo = 20, k = 2, hashValue = 0 Output: "ee" Explanation: The hash of "ee" can be computed to be hash("ee", 7, 20) = (5 * 1 + 5 * 7) mod 20 = 40 mod 20 = 0. "ee" is the first substring of length 2 with hashValue 0. Hence, we return "ee". Example 2: Input: s = "fbxzaad", power = 31, modulo = 100, k = 3, hashValue = 32 Output: "fbx" Explanation: The hash of "fbx" can be computed to be hash("fbx", 31, 100) = (6 * 1 + 2 * 31 + 24 * 312) mod 100 = 23132 mod 100 = 32. The hash of "bxz" can be computed to be hash("bxz", 31, 100) = (2 * 1 + 24 * 31 + 26 * 312) mod 100 = 25732 mod 100 = 32. "fbx" is the first substring of length 3 with hashValue 32. Hence, we return "fbx". Note that "bxz" also has a hash of 32 but it appears later than "fbx".   Constraints: 1 <= k <= s.length <= 2 * 10000 1 <= power, modulo <= 10^9 0 <= hashValue < modulo s consists of lowercase English letters only. The test cases are generated such that an answer always exists.
class Solution(object): def subStrHash(self, s, power, modulo, k, hashValue): """ :type s: str :type power: int :type modulo: int :type k: int :type hashValue: int :rtype: str """ a = [1+ord(ch)-ord('a') for ch in s] b = [1] * (k+1) for i in xrange(1, k+1): b[i] = (b[i-1] * power) % modulo n = len(a) h = sum(a[n-k+i]*b[i] for i in xrange(k)) r = n-k for i in xrange(n-k-1, -1, -1): h = (h*power + a[i] - a[i+k]*b[k]) % modulo if h == hashValue: r = i return s[r:r+k]
ab2f8e
88ae4e
The hash of a 0-indexed string s of length k, given integers p and m, is computed using the following function: hash(s, p, m) = (val(s[0]) * p0 + val(s[1]) * p1 + ... + val(s[k-1]) * pk-1) mod m. Where val(s[i]) represents the index of s[i] in the alphabet from val('a') = 1 to val('z') = 26. You are given a string s and the integers power, modulo, k, and hashValue. Return sub, the first substring of s of length k such that hash(sub, power, modulo) == hashValue. The test cases will be generated such that an answer always exists. A substring is a contiguous non-empty sequence of characters within a string.   Example 1: Input: s = "leetcode", power = 7, modulo = 20, k = 2, hashValue = 0 Output: "ee" Explanation: The hash of "ee" can be computed to be hash("ee", 7, 20) = (5 * 1 + 5 * 7) mod 20 = 40 mod 20 = 0. "ee" is the first substring of length 2 with hashValue 0. Hence, we return "ee". Example 2: Input: s = "fbxzaad", power = 31, modulo = 100, k = 3, hashValue = 32 Output: "fbx" Explanation: The hash of "fbx" can be computed to be hash("fbx", 31, 100) = (6 * 1 + 2 * 31 + 24 * 312) mod 100 = 23132 mod 100 = 32. The hash of "bxz" can be computed to be hash("bxz", 31, 100) = (2 * 1 + 24 * 31 + 26 * 312) mod 100 = 25732 mod 100 = 32. "fbx" is the first substring of length 3 with hashValue 32. Hence, we return "fbx". Note that "bxz" also has a hash of 32 but it appears later than "fbx".   Constraints: 1 <= k <= s.length <= 2 * 10000 1 <= power, modulo <= 10^9 0 <= hashValue < modulo s consists of lowercase English letters only. The test cases are generated such that an answer always exists.
class Solution: def subStrHash(self, s: str, power: int, modulo: int, k: int, hashValue: int) -> str: n = len(s) h = 0 pos = -1 for i in reversed(range(n)): h = (h * power + (ord(s[i]) - ord('a') + 1)) % modulo if i + k < n: h = (h - pow(power, k, modulo) * (ord(s[i + k]) - ord('a') + 1)) % modulo if h == hashValue: pos = i return s[pos:pos+k]
44081f
75af3e
You are given two positive integer arrays nums and numsDivide. You can delete any number of elements from nums. Return the minimum number of deletions such that the smallest element in nums divides all the elements of numsDivide. If this is not possible, return -1. Note that an integer x divides y if y % x == 0.   Example 1: Input: nums = [2,3,2,4,3], numsDivide = [9,6,9,3,15] Output: 2 Explanation: The smallest element in [2,3,2,4,3] is 2, which does not divide all the elements of numsDivide. We use 2 deletions to delete the elements in nums that are equal to 2 which makes nums = [3,4,3]. The smallest element in [3,4,3] is 3, which divides all the elements of numsDivide. It can be shown that 2 is the minimum number of deletions needed. Example 2: Input: nums = [4,3,6], numsDivide = [8,2,6,10] Output: -1 Explanation: We want the smallest element in nums to divide all the elements of numsDivide. There is no way to delete elements from nums to allow this.   Constraints: 1 <= nums.length, numsDivide.length <= 100000 1 <= nums[i], numsDivide[i] <= 10^9
class Solution: def minOperations(self, nums: List[int], numsDivide: List[int]) -> int: target=numsDivide[0] for i in numsDivide[1:]:target=gcd(target,i) nums.sort() for i,v in enumerate(nums): if target%v==0: return i return -1
c8bbff
75af3e
You are given two positive integer arrays nums and numsDivide. You can delete any number of elements from nums. Return the minimum number of deletions such that the smallest element in nums divides all the elements of numsDivide. If this is not possible, return -1. Note that an integer x divides y if y % x == 0.   Example 1: Input: nums = [2,3,2,4,3], numsDivide = [9,6,9,3,15] Output: 2 Explanation: The smallest element in [2,3,2,4,3] is 2, which does not divide all the elements of numsDivide. We use 2 deletions to delete the elements in nums that are equal to 2 which makes nums = [3,4,3]. The smallest element in [3,4,3] is 3, which divides all the elements of numsDivide. It can be shown that 2 is the minimum number of deletions needed. Example 2: Input: nums = [4,3,6], numsDivide = [8,2,6,10] Output: -1 Explanation: We want the smallest element in nums to divide all the elements of numsDivide. There is no way to delete elements from nums to allow this.   Constraints: 1 <= nums.length, numsDivide.length <= 100000 1 <= nums[i], numsDivide[i] <= 10^9
class Solution(object): def minOperations(self, nums, numsDivide): """ :type nums: List[int] :type numsDivide: List[int] :rtype: int """ nums.sort() h = numsDivide[0] def g(a, b): return g(b, a % b) if a % b else b for n in numsDivide: h = g(h, n) for i in range(0, len(nums)): if not h % nums[i]: return i return -1
3d82af
162caf
Alice and Bob take turns playing a game, with Alice starting first. There are n stones arranged in a row. On each player's turn, they can remove either the leftmost stone or the rightmost stone from the row and receive points equal to the sum of the remaining stones' values in the row. The winner is the one with the higher score when there are no stones left to remove. Bob found that he will always lose this game (poor Bob, he always loses), so he decided to minimize the score's difference. Alice's goal is to maximize the difference in the score. Given an array of integers stones where stones[i] represents the value of the ith stone from the left, return the difference in Alice and Bob's score if they both play optimally.   Example 1: Input: stones = [5,3,1,4,2] Output: 6 Explanation: - Alice removes 2 and gets 5 + 3 + 1 + 4 = 13 points. Alice = 13, Bob = 0, stones = [5,3,1,4]. - Bob removes 5 and gets 3 + 1 + 4 = 8 points. Alice = 13, Bob = 8, stones = [3,1,4]. - Alice removes 3 and gets 1 + 4 = 5 points. Alice = 18, Bob = 8, stones = [1,4]. - Bob removes 1 and gets 4 points. Alice = 18, Bob = 12, stones = [4]. - Alice removes 4 and gets 0 points. Alice = 18, Bob = 12, stones = []. The score difference is 18 - 12 = 6. Example 2: Input: stones = [7,90,5,1,100,10,10,2] Output: 122   Constraints: n == stones.length 2 <= n <= 1000 1 <= stones[i] <= 1000
class Solution: def stoneGameVII(self, stones: List[int]) -> int: n = len(stones) sum = [0] * (n + 1) for i in range(n): sum[i + 1] = sum[i] + stones[i] def get(l, r): return sum[r + 1] - sum[l] @cache def dp(l, r): if l == r: return 0 return max(get(l + 1, r) - dp(l + 1, r), get(l, r - 1) - dp(l, r - 1)) ans = dp(0, n - 1) dp.cache_clear() return ans
cede1c
162caf
Alice and Bob take turns playing a game, with Alice starting first. There are n stones arranged in a row. On each player's turn, they can remove either the leftmost stone or the rightmost stone from the row and receive points equal to the sum of the remaining stones' values in the row. The winner is the one with the higher score when there are no stones left to remove. Bob found that he will always lose this game (poor Bob, he always loses), so he decided to minimize the score's difference. Alice's goal is to maximize the difference in the score. Given an array of integers stones where stones[i] represents the value of the ith stone from the left, return the difference in Alice and Bob's score if they both play optimally.   Example 1: Input: stones = [5,3,1,4,2] Output: 6 Explanation: - Alice removes 2 and gets 5 + 3 + 1 + 4 = 13 points. Alice = 13, Bob = 0, stones = [5,3,1,4]. - Bob removes 5 and gets 3 + 1 + 4 = 8 points. Alice = 13, Bob = 8, stones = [3,1,4]. - Alice removes 3 and gets 1 + 4 = 5 points. Alice = 18, Bob = 8, stones = [1,4]. - Bob removes 1 and gets 4 points. Alice = 18, Bob = 12, stones = [4]. - Alice removes 4 and gets 0 points. Alice = 18, Bob = 12, stones = []. The score difference is 18 - 12 = 6. Example 2: Input: stones = [7,90,5,1,100,10,10,2] Output: 122   Constraints: n == stones.length 2 <= n <= 1000 1 <= stones[i] <= 1000
class Solution(object): def stoneGameVII(self, stones): """ :type stones: List[int] :rtype: int """ a = stones n = len(a) s = [0] + a for i in xrange(n): s[i+1] += s[i] f = [0] * n for k in xrange(2, 1+n): f = [max(s[i+k]-s[i+1]-f[i+1], s[i+k-1]-s[i]-f[i]) for i in xrange(1+n-k)] return f[0]
dd4582
ee423f
Given an integer array nums and an integer k, return the number of good subarrays of nums. A good array is an array where the number of different integers in that array is exactly k. For example, [1,2,3,1,2] has 3 different integers: 1, 2, and 3. A subarray is a contiguous part of an array.   Example 1: Input: nums = [1,2,1,2,3], k = 2 Output: 7 Explanation: Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2] Example 2: Input: nums = [1,2,1,3,4], k = 3 Output: 3 Explanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].   Constraints: 1 <= nums.length <= 2 * 10000 1 <= nums[i], k <= nums.length
class Solution(object): def subarraysWithKDistinct(self, A, K): """ :type A: List[int] :type K: int :rtype: int """ from collections import defaultdict def f(arr, need): c = defaultdict(int) front = 0 back = 0 while back < len(arr) and len(c) < need: c[arr[back]] += 1 back += 1 count = 0 if len(c) == need: count += len(arr) - back + 1 while front < len(arr): c[arr[front]] -= 1 if c[arr[front]] == 0: del c[arr[front]] front += 1 while back < len(arr) and len(c) < need: c[arr[back]] += 1 back += 1 if len(c) == need: count += len(arr) - back + 1 return count return f(A, K) - f(A, K+1)
012460
ee423f
Given an integer array nums and an integer k, return the number of good subarrays of nums. A good array is an array where the number of different integers in that array is exactly k. For example, [1,2,3,1,2] has 3 different integers: 1, 2, and 3. A subarray is a contiguous part of an array.   Example 1: Input: nums = [1,2,1,2,3], k = 2 Output: 7 Explanation: Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2] Example 2: Input: nums = [1,2,1,3,4], k = 3 Output: 3 Explanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].   Constraints: 1 <= nums.length <= 2 * 10000 1 <= nums[i], k <= nums.length
class Solution: def subarraysWithKDistinct(self, A: 'List[int]', K: 'int') -> 'int': def work(A, K): n = len(A) j = 0 cnt = [0] * (n + 1) ans = 0 wd = 0 for i in range(n): cnt[A[i]] += 1 if cnt[A[i]] == 1: wd += 1 while wd > K: cnt[A[j]] -= 1 if cnt[A[j]] == 0: wd -= 1 j += 1 ans += i - j + 1 return ans return work(A, K) - work(A, K - 1)
7887aa
5afeac
You are given a 0-indexed array of positive integers tasks, representing tasks that need to be completed in order, where tasks[i] represents the type of the ith task. You are also given a positive integer space, which represents the minimum number of days that must pass after the completion of a task before another task of the same type can be performed. Each day, until all tasks have been completed, you must either: Complete the next task from tasks, or Take a break. Return the minimum number of days needed to complete all tasks.   Example 1: Input: tasks = [1,2,1,2,3,1], space = 3 Output: 9 Explanation: One way to complete all tasks in 9 days is as follows: Day 1: Complete the 0th task. Day 2: Complete the 1st task. Day 3: Take a break. Day 4: Take a break. Day 5: Complete the 2nd task. Day 6: Complete the 3rd task. Day 7: Take a break. Day 8: Complete the 4th task. Day 9: Complete the 5th task. It can be shown that the tasks cannot be completed in less than 9 days. Example 2: Input: tasks = [5,8,8,5], space = 2 Output: 6 Explanation: One way to complete all tasks in 6 days is as follows: Day 1: Complete the 0th task. Day 2: Complete the 1st task. Day 3: Take a break. Day 4: Take a break. Day 5: Complete the 2nd task. Day 6: Complete the 3rd task. It can be shown that the tasks cannot be completed in less than 6 days.   Constraints: 1 <= tasks.length <= 100000 1 <= tasks[i] <= 10^9 1 <= space <= tasks.length
class Solution: def taskSchedulerII(self, tasks: List[int], space: int) -> int: d = defaultdict(lambda: -inf) day = 0 for i in tasks: day = max(day+1, d[i]+space+1) d[i] = day return day
197f23
5afeac
You are given a 0-indexed array of positive integers tasks, representing tasks that need to be completed in order, where tasks[i] represents the type of the ith task. You are also given a positive integer space, which represents the minimum number of days that must pass after the completion of a task before another task of the same type can be performed. Each day, until all tasks have been completed, you must either: Complete the next task from tasks, or Take a break. Return the minimum number of days needed to complete all tasks.   Example 1: Input: tasks = [1,2,1,2,3,1], space = 3 Output: 9 Explanation: One way to complete all tasks in 9 days is as follows: Day 1: Complete the 0th task. Day 2: Complete the 1st task. Day 3: Take a break. Day 4: Take a break. Day 5: Complete the 2nd task. Day 6: Complete the 3rd task. Day 7: Take a break. Day 8: Complete the 4th task. Day 9: Complete the 5th task. It can be shown that the tasks cannot be completed in less than 9 days. Example 2: Input: tasks = [5,8,8,5], space = 2 Output: 6 Explanation: One way to complete all tasks in 6 days is as follows: Day 1: Complete the 0th task. Day 2: Complete the 1st task. Day 3: Take a break. Day 4: Take a break. Day 5: Complete the 2nd task. Day 6: Complete the 3rd task. It can be shown that the tasks cannot be completed in less than 6 days.   Constraints: 1 <= tasks.length <= 100000 1 <= tasks[i] <= 10^9 1 <= space <= tasks.length
class Solution(object): def taskSchedulerII(self, tasks, space): """ :type tasks: List[int] :type space: int :rtype: int """ dic = {} ans = 0 for t in tasks: if t in dic and dic[t] + space > ans: ans = dic[t] + space ans += 1 dic[t] = ans return ans
6fa8dd
d74660
You are given an integer array nums. You have an integer array arr of the same length with all values set to 0 initially. You also have the following modify function: You want to use the modify function to covert arr to nums using the minimum number of calls. Return the minimum number of function calls to make nums from arr. The test cases are generated so that the answer fits in a 32-bit signed integer.   Example 1: Input: nums = [1,5] Output: 5 Explanation: Increment by 1 (second element): [0, 0] to get [0, 1] (1 operation). Double all the elements: [0, 1] -> [0, 2] -> [0, 4] (2 operations). Increment by 1 (both elements) [0, 4] -> [1, 4] -> [1, 5] (2 operations). Total of operations: 1 + 2 + 2 = 5. Example 2: Input: nums = [2,2] Output: 3 Explanation: Increment by 1 (both elements) [0, 0] -> [0, 1] -> [1, 1] (2 operations). Double all the elements: [1, 1] -> [2, 2] (1 operation). Total of operations: 2 + 1 = 3. Example 3: Input: nums = [4,2,5] Output: 6 Explanation: (initial)[0,0,0] -> [1,0,0] -> [1,0,1] -> [2,0,2] -> [2,1,2] -> [4,2,4] -> [4,2,5](nums).   Constraints: 1 <= nums.length <= 100000 0 <= nums[i] <= 10^9
class Solution(object): def minOperations(self, A): ans = 0 bns = 0 for x in A: b = bin(x) ans += b.count('1') if x: bns = max(bns, len(b) - 2) return ans + max(bns-1,0)
ad03d3
d74660
You are given an integer array nums. You have an integer array arr of the same length with all values set to 0 initially. You also have the following modify function: You want to use the modify function to covert arr to nums using the minimum number of calls. Return the minimum number of function calls to make nums from arr. The test cases are generated so that the answer fits in a 32-bit signed integer.   Example 1: Input: nums = [1,5] Output: 5 Explanation: Increment by 1 (second element): [0, 0] to get [0, 1] (1 operation). Double all the elements: [0, 1] -> [0, 2] -> [0, 4] (2 operations). Increment by 1 (both elements) [0, 4] -> [1, 4] -> [1, 5] (2 operations). Total of operations: 1 + 2 + 2 = 5. Example 2: Input: nums = [2,2] Output: 3 Explanation: Increment by 1 (both elements) [0, 0] -> [0, 1] -> [1, 1] (2 operations). Double all the elements: [1, 1] -> [2, 2] (1 operation). Total of operations: 2 + 1 = 3. Example 3: Input: nums = [4,2,5] Output: 6 Explanation: (initial)[0,0,0] -> [1,0,0] -> [1,0,1] -> [2,0,2] -> [2,1,2] -> [4,2,4] -> [4,2,5](nums).   Constraints: 1 <= nums.length <= 100000 0 <= nums[i] <= 10^9
class Solution: def minOperations(self, nums: List[int]) -> int: nums.sort() count = 0 double = 0 for x in nums: cd = 0 while x > 0: if x % 2 == 1: count += 1 x //= 2 cd += 1 double = max(cd, double) return count + (double - 1)
d59768
e15c57
Given a binary tree root and an integer target, delete all the leaf nodes with value target. Note that once you delete a leaf node with value target, if its parent node becomes a leaf node and has the value target, it should also be deleted (you need to continue doing that until you cannot).   Example 1: Input: root = [1,2,3,2,null,2,4], target = 2 Output: [1,null,3,null,4] Explanation: Leaf nodes in green with value (target = 2) are removed (Picture in left). After removing, new nodes become leaf nodes with value (target = 2) (Picture in center). Example 2: Input: root = [1,3,3,3,2], target = 3 Output: [1,3,null,null,2] Example 3: Input: root = [1,2,null,2,null,2], target = 2 Output: [1] Explanation: Leaf nodes in green with value (target = 2) are removed at each step.   Constraints: The number of nodes in the tree is in the range [1, 3000]. 1 <= Node.val, target <= 1000
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def removeLeafNodes(self, root, target): """ :type root: TreeNode :type target: int :rtype: TreeNode """ def f(node): if not node: return None node.left = f(node.left) node.right = f(node.right) if node.left or node.right: return node return None if node.val == target else node return f(root)
e3fb15
e15c57
Given a binary tree root and an integer target, delete all the leaf nodes with value target. Note that once you delete a leaf node with value target, if its parent node becomes a leaf node and has the value target, it should also be deleted (you need to continue doing that until you cannot).   Example 1: Input: root = [1,2,3,2,null,2,4], target = 2 Output: [1,null,3,null,4] Explanation: Leaf nodes in green with value (target = 2) are removed (Picture in left). After removing, new nodes become leaf nodes with value (target = 2) (Picture in center). Example 2: Input: root = [1,3,3,3,2], target = 3 Output: [1,3,null,null,2] Example 3: Input: root = [1,2,null,2,null,2], target = 2 Output: [1] Explanation: Leaf nodes in green with value (target = 2) are removed at each step.   Constraints: The number of nodes in the tree is in the range [1, 3000]. 1 <= Node.val, target <= 1000
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def removeLeafNodes(self, root: TreeNode, target: int) -> TreeNode: if root: root.left = self.removeLeafNodes(root.left, target) root.right = self.removeLeafNodes(root.right, target) if not root.left and not root.right and root.val == target: return None return root
50165a
966337
There is a strange printer with the following two special requirements: On each turn, the printer will print a solid rectangular pattern of a single color on the grid. This will cover up the existing colors in the rectangle. Once the printer has used a color for the above operation, the same color cannot be used again. You are given a m x n matrix targetGrid, where targetGrid[row][col] is the color in the position (row, col) of the grid. Return true if it is possible to print the matrix targetGrid, otherwise, return false.   Example 1: Input: targetGrid = [[1,1,1,1],[1,2,2,1],[1,2,2,1],[1,1,1,1]] Output: true Example 2: Input: targetGrid = [[1,1,1,1],[1,1,3,3],[1,1,3,4],[5,5,1,4]] Output: true Example 3: Input: targetGrid = [[1,2,1],[2,1,2],[1,2,1]] Output: false Explanation: It is impossible to form targetGrid because it is not allowed to print the same color in different turns.   Constraints: m == targetGrid.length n == targetGrid[i].length 1 <= m, n <= 60 1 <= targetGrid[row][col] <= 60
INF = 1 << 60 class Solution: def isPrintable(self, grid: List[List[int]]) -> bool: m = len(grid) n = len(grid[0]) cols = set() for i, j in product(range(m), range(n)): cols.add(grid[i][j]) D = {v : i for i, v in enumerate(sorted(cols))} for i, j in product(range(m), range(n)): grid[i][j] = D[grid[i][j]] col = len(cols) left = [INF] * col right = [-INF] * col up = [INF] * col down = [-INF] * col for i, j in product(range(m), range(n)): c = grid[i][j] left[c] = min(left[c], j) right[c] = max(right[c], j) up[c] = min(up[c], i) down[c] = max(down[c], i) E = [set() for _ in range(col)] for c in range(col): for i, j in product(range(up[c], down[c] + 1), range(left[c], right[c] + 1)): if grid[i][j] != c: E[c].add(grid[i][j]) n = col deg = [0] * n for v in range(n): for nv in E[v]: deg[nv] += 1 ans = list(v for v in range(col) if deg[v]==0) deq = deque(ans) used = [0]*col while deq: v = deq.popleft() for t in E[v]: deg[t] -= 1 if deg[t]==0: deq.append(t) ans.append(t) return len(ans) == col
9b08ca
966337
There is a strange printer with the following two special requirements: On each turn, the printer will print a solid rectangular pattern of a single color on the grid. This will cover up the existing colors in the rectangle. Once the printer has used a color for the above operation, the same color cannot be used again. You are given a m x n matrix targetGrid, where targetGrid[row][col] is the color in the position (row, col) of the grid. Return true if it is possible to print the matrix targetGrid, otherwise, return false.   Example 1: Input: targetGrid = [[1,1,1,1],[1,2,2,1],[1,2,2,1],[1,1,1,1]] Output: true Example 2: Input: targetGrid = [[1,1,1,1],[1,1,3,3],[1,1,3,4],[5,5,1,4]] Output: true Example 3: Input: targetGrid = [[1,2,1],[2,1,2],[1,2,1]] Output: false Explanation: It is impossible to form targetGrid because it is not allowed to print the same color in different turns.   Constraints: m == targetGrid.length n == targetGrid[i].length 1 <= m, n <= 60 1 <= targetGrid[row][col] <= 60
class Solution(object): def isPrintable(self, targetGrid): """ :type targetGrid: List[List[int]] :rtype: bool """ minx, maxx, miny, maxy = [-1]*61, [-1]*61, [-1]*61, [-1]*61 m, n = len(targetGrid), len(targetGrid[0]) for i in range(m): for j in range(n): c = targetGrid[i][j] if minx[c]==-1 or minx[c]>i: minx[c]=i if maxx[c]==-1 or maxx[c]<i: maxx[c]=i if miny[c]==-1 or miny[c]>j: miny[c]=j if maxy[c]==-1 or maxy[c]<j: maxy[c]=j # print minx[1], maxx[1], minx[60], maxx[60] # print miny[1], maxy[1], miny[60], maxy[60] while True: c = 1 relax = False while c<=60: if minx[c]!=-1: match = True for i in range(minx[c], maxx[c]+1): for j in range(miny[c], maxy[c]+1): if targetGrid[i][j]==c or targetGrid[i][j]==-1: pass else: match=False break if not match: break if match: relax = True # print "paint", c for i in range(minx[c], maxx[c]+1): for j in range(miny[c], maxy[c]+1): targetGrid[i][j]=-1 minx[c]=-1 c+=1 if not relax: break # print targetGrid for i in range(m): for j in range(n): if targetGrid[i][j]!=-1: return False return True
da1f73
11c3d3
You are given an integer hoursBefore, the number of hours you have to travel to your meeting. To arrive at your meeting, you have to travel through n roads. The road lengths are given as an integer array dist of length n, where dist[i] describes the length of the ith road in kilometers. In addition, you are given an integer speed, which is the speed (in km/h) you will travel at. After you travel road i, you must rest and wait for the next integer hour before you can begin traveling on the next road. Note that you do not have to rest after traveling the last road because you are already at the meeting. For example, if traveling a road takes 1.4 hours, you must wait until the 2 hour mark before traveling the next road. If traveling a road takes exactly 2 hours, you do not need to wait. However, you are allowed to skip some rests to be able to arrive on time, meaning you do not need to wait for the next integer hour. Note that this means you may finish traveling future roads at different hour marks. For example, suppose traveling the first road takes 1.4 hours and traveling the second road takes 0.6 hours. Skipping the rest after the first road will mean you finish traveling the second road right at the 2 hour mark, letting you start traveling the third road immediately. Return the minimum number of skips required to arrive at the meeting on time, or -1 if it is impossible.   Example 1: Input: dist = [1,3,2], speed = 4, hoursBefore = 2 Output: 1 Explanation: Without skipping any rests, you will arrive in (1/4 + 3/4) + (3/4 + 1/4) + (2/4) = 2.5 hours. You can skip the first rest to arrive in ((1/4 + 0) + (3/4 + 0)) + (2/4) = 1.5 hours. Note that the second rest is shortened because you finish traveling the second road at an integer hour due to skipping the first rest. Example 2: Input: dist = [7,3,5,5], speed = 2, hoursBefore = 10 Output: 2 Explanation: Without skipping any rests, you will arrive in (7/2 + 1/2) + (3/2 + 1/2) + (5/2 + 1/2) + (5/2) = 11.5 hours. You can skip the first and third rest to arrive in ((7/2 + 0) + (3/2 + 0)) + ((5/2 + 0) + (5/2)) = 10 hours. Example 3: Input: dist = [7,3,5,5], speed = 1, hoursBefore = 10 Output: -1 Explanation: It is impossible to arrive at the meeting on time even if you skip all the rests.   Constraints: n == dist.length 1 <= n <= 1000 1 <= dist[i] <= 100000 1 <= speed <= 1000000 1 <= hoursBefore <= 10^7
class Solution: def minSkips(self, dist: List[int], speed: int, hoursBefore: int) -> int: n = len(dist) dp = [0 for _ in range(n)] for i in range(n): newdp = dp[:] newdp[0] = math.ceil(dp[0] / speed) * speed + dist[i] for j in range(1, n): way1 = math.ceil(dp[j] / speed) * speed + dist[i] way2 = dp[j-1] + dist[i] newdp[j] = min(way1, way2) dp = newdp #print(dp) for i in range(n): if dp[i] / speed <= hoursBefore: return i return -1
f4585d
11c3d3
You are given an integer hoursBefore, the number of hours you have to travel to your meeting. To arrive at your meeting, you have to travel through n roads. The road lengths are given as an integer array dist of length n, where dist[i] describes the length of the ith road in kilometers. In addition, you are given an integer speed, which is the speed (in km/h) you will travel at. After you travel road i, you must rest and wait for the next integer hour before you can begin traveling on the next road. Note that you do not have to rest after traveling the last road because you are already at the meeting. For example, if traveling a road takes 1.4 hours, you must wait until the 2 hour mark before traveling the next road. If traveling a road takes exactly 2 hours, you do not need to wait. However, you are allowed to skip some rests to be able to arrive on time, meaning you do not need to wait for the next integer hour. Note that this means you may finish traveling future roads at different hour marks. For example, suppose traveling the first road takes 1.4 hours and traveling the second road takes 0.6 hours. Skipping the rest after the first road will mean you finish traveling the second road right at the 2 hour mark, letting you start traveling the third road immediately. Return the minimum number of skips required to arrive at the meeting on time, or -1 if it is impossible.   Example 1: Input: dist = [1,3,2], speed = 4, hoursBefore = 2 Output: 1 Explanation: Without skipping any rests, you will arrive in (1/4 + 3/4) + (3/4 + 1/4) + (2/4) = 2.5 hours. You can skip the first rest to arrive in ((1/4 + 0) + (3/4 + 0)) + (2/4) = 1.5 hours. Note that the second rest is shortened because you finish traveling the second road at an integer hour due to skipping the first rest. Example 2: Input: dist = [7,3,5,5], speed = 2, hoursBefore = 10 Output: 2 Explanation: Without skipping any rests, you will arrive in (7/2 + 1/2) + (3/2 + 1/2) + (5/2 + 1/2) + (5/2) = 11.5 hours. You can skip the first and third rest to arrive in ((7/2 + 0) + (3/2 + 0)) + ((5/2 + 0) + (5/2)) = 10 hours. Example 3: Input: dist = [7,3,5,5], speed = 1, hoursBefore = 10 Output: -1 Explanation: It is impossible to arrive at the meeting on time even if you skip all the rests.   Constraints: n == dist.length 1 <= n <= 1000 1 <= dist[i] <= 100000 1 <= speed <= 1000000 1 <= hoursBefore <= 10^7
class Solution(object): def minSkips(self, dist, speed, hoursBefore): """ :type dist: List[int] :type speed: int :type hoursBefore: int :rtype: int """ total = hoursBefore * speed - dist.pop() if sum(dist) > total: return -1 align = lambda t: (-t) % speed + t n = len(dist) f = [0] * (n+1) for i in xrange(n): f[i+1] = f[i] + dist[i] for j in xrange(i, 0, -1): f[j] = min(align(f[j]+dist[i]), f[j-1]+dist[i]) f[0] = align(f[0]+dist[i]) for i in xrange(n+1): if f[i] <= total: return i return n
f7d9a0
f46d9b
A parentheses string is a non-empty string consisting only of '(' and ')'. It is valid if any of the following conditions is true: It is (). It can be written as AB (A concatenated with B), where A and B are valid parentheses strings. It can be written as (A), where A is a valid parentheses string. You are given a parentheses string s and a string locked, both of length n. locked is a binary string consisting only of '0's and '1's. For each index i of locked, If locked[i] is '1', you cannot change s[i]. But if locked[i] is '0', you can change s[i] to either '(' or ')'. Return true if you can make s a valid parentheses string. Otherwise, return false.   Example 1: Input: s = "))()))", locked = "010100" Output: true Explanation: locked[1] == '1' and locked[3] == '1', so we cannot change s[1] or s[3]. We change s[0] and s[4] to '(' while leaving s[2] and s[5] unchanged to make s valid. Example 2: Input: s = "()()", locked = "0000" Output: true Explanation: We do not need to make any changes because s is already valid. Example 3: Input: s = ")", locked = "0" Output: false Explanation: locked permits us to change s[0]. Changing s[0] to either '(' or ')' will not make s valid.   Constraints: n == s.length == locked.length 1 <= n <= 100000 s[i] is either '(' or ')'. locked[i] is either '0' or '1'.
class Solution: def canBeValid(self, s: str, locked: str) -> bool: n = len(s) if n%2: return False ok = 0 for i in range(n): if locked[i] == "0": ok += 1 elif s[i] == "(": ok += 1 else: if ok == 0: return False ok -= 1 ok = 0 for i in range(n-1,-1,-1): if locked[i] == "0": ok += 1 elif s[i] == ")": ok += 1 else: if ok == 0: return False ok -= 1 return True
fce7f7
f46d9b
A parentheses string is a non-empty string consisting only of '(' and ')'. It is valid if any of the following conditions is true: It is (). It can be written as AB (A concatenated with B), where A and B are valid parentheses strings. It can be written as (A), where A is a valid parentheses string. You are given a parentheses string s and a string locked, both of length n. locked is a binary string consisting only of '0's and '1's. For each index i of locked, If locked[i] is '1', you cannot change s[i]. But if locked[i] is '0', you can change s[i] to either '(' or ')'. Return true if you can make s a valid parentheses string. Otherwise, return false.   Example 1: Input: s = "))()))", locked = "010100" Output: true Explanation: locked[1] == '1' and locked[3] == '1', so we cannot change s[1] or s[3]. We change s[0] and s[4] to '(' while leaving s[2] and s[5] unchanged to make s valid. Example 2: Input: s = "()()", locked = "0000" Output: true Explanation: We do not need to make any changes because s is already valid. Example 3: Input: s = ")", locked = "0" Output: false Explanation: locked permits us to change s[0]. Changing s[0] to either '(' or ')' will not make s valid.   Constraints: n == s.length == locked.length 1 <= n <= 100000 s[i] is either '(' or ')'. locked[i] is either '0' or '1'.
class Solution(object): def canBeValid(self, s, locked): """ :type s: str :type locked: str :rtype: bool """ n = len(s) cntOpen, cntClose = 0, 0 for i in range(n): if locked[i] == "1" and s[i] == "(": cntOpen += 1 if locked[i] == "1" and s[i] == ")": cntClose += 1 if n%2: return False cntOpen = n//2 - cntOpen cntClose = n//2 - cntClose if cntOpen < 0 or cntClose < 0: return False degs = 0 for i in range(n): if locked[i] == "1": if s[i] == "(": degs += 1 else: degs -= 1 else: if cntOpen > 0: degs += 1 cntOpen -= 1 else: degs -= 1 cntClose -= 1 if degs < 0: return False return True
a8acba
a6cf7e
Given an array rectangles where rectangles[i] = [xi, yi, ai, bi] represents an axis-aligned rectangle. The bottom-left point of the rectangle is (xi, yi) and the top-right point of it is (ai, bi). Return true if all the rectangles together form an exact cover of a rectangular region.   Example 1: Input: rectangles = [[1,1,3,3],[3,1,4,2],[3,2,4,4],[1,3,2,4],[2,3,3,4]] Output: true Explanation: All 5 rectangles together form an exact cover of a rectangular region. Example 2: Input: rectangles = [[1,1,2,3],[1,3,2,4],[3,1,4,2],[3,2,4,4]] Output: false Explanation: Because there is a gap between the two rectangular regions. Example 3: Input: rectangles = [[1,1,3,3],[3,1,4,2],[1,3,2,4],[2,2,4,4]] Output: false Explanation: Because two of the rectangles overlap with each other.   Constraints: 1 <= rectangles.length <= 2 * 10000 rectangles[i].length == 4 -100000 <= xi, yi, ai, bi <= 100000
class Solution(object): def isRectangleCover(self, rectangles): """ :type rectangles: List[List[int]] :rtype: bool """ d={} for r in rectangles: self.put(d,r[0],r[1]) self.put(d,r[2],r[3]) self.put(d,r[0],r[3]) self.put(d,r[2],r[1]) cnt=0 for i in d: if d[i]%2!=0: cnt+=1 return cnt==4 or cnt==4 or cnt==2 def put(self,d,x,y): if (x,y) not in d: d[(x,y)]=1 else: d[(x,y)]+=1
3751f8
57ec58
Given a 2D grid of 0s and 1s, return the number of elements in the largest square subgrid that has all 1s on its border, or 0 if such a subgrid doesn't exist in the grid.   Example 1: Input: grid = [[1,1,1],[1,0,1],[1,1,1]] Output: 9 Example 2: Input: grid = [[1,1,0,0]] Output: 1   Constraints: 1 <= grid.length <= 100 1 <= grid[0].length <= 100 grid[i][j] is 0 or 1
class Solution: def largest1BorderedSquare(self, grid: List[List[int]]) -> int: # up[i][j] stores number of 1s up. m = len(grid) n = len(grid[0]) up = [[0 for _ in range(n)] for _ in range(m)] for row in range(m): for col in range(n): if grid[row][col] == 0: continue if row == 0: up[row][col] = 1 else: up[row][col] = 1 + up[row - 1][col] left = [[0 for _ in range(n)] for _ in range(m)] for row in range(m): for col in range(n): if grid[row][col] == 0: continue if col == 0: left[row][col] = 1 else: left[row][col] = 1 + left[row][col - 1] for l in range(min(m, n), -1, -1): # Check if there exists l. for row in range(l - 1, m): for col in range(l - 1, n): if up[row][col] >= l and left[row][col] >= l and up[row][col - l + 1] >= l and left[row - l + 1][col] >= l: return l ** 2 return 0
11792e
57ec58
Given a 2D grid of 0s and 1s, return the number of elements in the largest square subgrid that has all 1s on its border, or 0 if such a subgrid doesn't exist in the grid.   Example 1: Input: grid = [[1,1,1],[1,0,1],[1,1,1]] Output: 9 Example 2: Input: grid = [[1,1,0,0]] Output: 1   Constraints: 1 <= grid.length <= 100 1 <= grid[0].length <= 100 grid[i][j] is 0 or 1
from copy import deepcopy class Solution(object): def largest1BorderedSquare(self, grid): """ :type grid: List[List[int]] :rtype: int """ n, m = len(grid), len(grid[0]) d = deepcopy(grid) r = deepcopy(grid) for i in xrange(n-2, -1, -1): for j in xrange(m): if grid[i][j] == 0: continue d[i][j] = 1 + d[i+1][j] for i in xrange(n): for j in xrange(m-2, -1, -1): if grid[i][j] == 0: continue r[i][j] = 1 + r[i][j+1] def f(i, j): if grid[i][j] == 0: return 0 for k in xrange(min(d[i][j], r[i][j]), 0, -1): if d[i][j+k-1] >= k and r[i+k-1][j] >= k: return k return 0 best = 0 for i in xrange(n): for j in xrange(m): best = max(best, f(i, j)) return best**2
5fba81
9061b9
Given an m x n picture consisting of black 'B' and white 'W' pixels and an integer target, return the number of black lonely pixels. A black lonely pixel is a character 'B' that located at a specific position (r, c) where: Row r and column c both contain exactly target black pixels. For all rows that have a black pixel at column c, they should be exactly the same as row r. Example 1: Input: picture = [["W","B","W","B","B","W"],["W","B","W","B","B","W"],["W","B","W","B","B","W"],["W","W","B","W","B","W"]], target = 3 Output: 6 Explanation: All the green 'B' are the black pixels we need (all 'B's at column 1 and 3). Take 'B' at row r = 0 and column c = 1 as an example: - Rule 1, row r = 0 and column c = 1 both have exactly target = 3 black pixels. - Rule 2, the rows have black pixel at column c = 1 are row 0, row 1 and row 2. They are exactly the same as row r = 0. Example 2: Input: picture = [["W","W","B"],["W","W","B"],["W","W","B"]], target = 1 Output: 0 Constraints: m == picture.length n == picture[i].length 1 <= m, n <= 200 picture[i][j] is 'W' or 'B'. 1 <= target <= min(m, n)
class Solution(object): def findBlackPixel(self, A, N): """ :type picture: List[List[str]] :type N: int :rtype: int """ B = zip(*A) Ar = [] Bc = [] for r, row in enumerate(A): Ar.append([c for c,val in enumerate(row) if val == 'B']) for c, col in enumerate(B): Bc.append([r for r,val in enumerate(col) if val == 'B']) ##print Ar #print Bc #print '.' ans = 0 for r,indexes in enumerate(Ar): if len(indexes) == N: for index in indexes: indexes2 = Bc[index] if len(indexes2) == N: if all(A[indexes2[0]] == A[i] for i in indexes2): ans += 1 #print 'yo', r, index,'.', indexes2 return ans
acf184
e39352
There are k workers who want to move n boxes from an old warehouse to a new one. You are given the two integers n and k, and a 2D integer array time of size k x 4 where time[i] = [leftToRighti, pickOldi, rightToLefti, putNewi]. The warehouses are separated by a river and connected by a bridge. The old warehouse is on the right bank of the river, and the new warehouse is on the left bank of the river. Initially, all k workers are waiting on the left side of the bridge. To move the boxes, the ith worker (0-indexed) can : Cross the bridge from the left bank (new warehouse) to the right bank (old warehouse) in leftToRighti minutes. Pick a box from the old warehouse and return to the bridge in pickOldi minutes. Different workers can pick up their boxes simultaneously. Cross the bridge from the right bank (old warehouse) to the left bank (new warehouse) in rightToLefti minutes. Put the box in the new warehouse and return to the bridge in putNewi minutes. Different workers can put their boxes simultaneously. A worker i is less efficient than a worker j if either condition is met: leftToRighti + rightToLefti > leftToRightj + rightToLeftj leftToRighti + rightToLefti == leftToRightj + rightToLeftj and i > j The following rules regulate the movement of the workers through the bridge : If a worker x reaches the bridge while another worker y is crossing the bridge, x waits at their side of the bridge. If the bridge is free, the worker waiting on the right side of the bridge gets to cross the bridge. If more than one worker is waiting on the right side, the one with the lowest efficiency crosses first. If the bridge is free and no worker is waiting on the right side, and at least one box remains at the old warehouse, the worker on the left side of the river gets to cross the bridge. If more than one worker is waiting on the left side, the one with the lowest efficiency crosses first. Return the instance of time at which the last worker reaches the left bank of the river after all n boxes have been put in the new warehouse.   Example 1: Input: n = 1, k = 3, time = [[1,1,2,1],[1,1,3,1],[1,1,4,1]] Output: 6 Explanation: From 0 to 1: worker 2 crosses the bridge from the left bank to the right bank. From 1 to 2: worker 2 picks up a box from the old warehouse. From 2 to 6: worker 2 crosses the bridge from the right bank to the left bank. From 6 to 7: worker 2 puts a box at the new warehouse. The whole process ends after 7 minutes. We return 6 because the problem asks for the instance of time at which the last worker reaches the left bank. Example 2: Input: n = 3, k = 2, time = [[1,9,1,8],[10,10,10,10]] Output: 50 Explanation: From 0  to 10: worker 1 crosses the bridge from the left bank to the right bank. From 10 to 20: worker 1 picks up a box from the old warehouse. From 10 to 11: worker 0 crosses the bridge from the left bank to the right bank. From 11 to 20: worker 0 picks up a box from the old warehouse. From 20 to 30: worker 1 crosses the bridge from the right bank to the left bank. From 30 to 40: worker 1 puts a box at the new warehouse. From 30 to 31: worker 0 crosses the bridge from the right bank to the left bank. From 31 to 39: worker 0 puts a box at the new warehouse. From 39 to 40: worker 0 crosses the bridge from the left bank to the right bank. From 40 to 49: worker 0 picks up a box from the old warehouse. From 49 to 50: worker 0 crosses the bridge from the right bank to the left bank. From 50 to 58: worker 0 puts a box at the new warehouse. The whole process ends after 58 minutes. We return 50 because the problem asks for the instance of time at which the last worker reaches the left bank.   Constraints: 1 <= n, k <= 10000 time.length == k time[i].length == 4 1 <= leftToRighti, pickOldi, rightToLefti, putNewi <= 1000
class Solution(object): def findCrossingTime(self, n, k, time): """ :type n: int :type k: int :type time: List[List[int]] :rtype: int """ a, f, l, r, m, s = 0, 0, [], [], [], [] for i in range(len(time)): heapq.heappush(m, (-time[i][0] - time[i][2], -i)) while n or r or s: f = min(l[0][0] if n and l else float('inf'), r[0][0] if r else float('inf')) if not s and (not r or r[0][0] > f) and (not n or not m and (not l or l[0][0] > f)) else f while l and l[0][0] <= f: heapq.heappush(m, (-time[l[0][1]][0] - time[l[0][1]][2], -heapq.heappop(l)[1])) while r and r[0][0] <= f: heapq.heappush(s, (-time[r[0][1]][0] - time[r[0][1]][2], -heapq.heappop(r)[1])) if s: f, a, i = f + time[-s[0][1]][2], a if n else max(a, f + time[-s[0][1]][2]), -heapq.heappop(s)[1] if n: heapq.heappush(l, (f + time[i][3], i)) else: f, n = f + time[-m[0][1]][0], n - 1 heapq.heappush(r, (f + time[-m[0][1]][1], -heapq.heappop(m)[1])) return a
be932d
e39352
There are k workers who want to move n boxes from an old warehouse to a new one. You are given the two integers n and k, and a 2D integer array time of size k x 4 where time[i] = [leftToRighti, pickOldi, rightToLefti, putNewi]. The warehouses are separated by a river and connected by a bridge. The old warehouse is on the right bank of the river, and the new warehouse is on the left bank of the river. Initially, all k workers are waiting on the left side of the bridge. To move the boxes, the ith worker (0-indexed) can : Cross the bridge from the left bank (new warehouse) to the right bank (old warehouse) in leftToRighti minutes. Pick a box from the old warehouse and return to the bridge in pickOldi minutes. Different workers can pick up their boxes simultaneously. Cross the bridge from the right bank (old warehouse) to the left bank (new warehouse) in rightToLefti minutes. Put the box in the new warehouse and return to the bridge in putNewi minutes. Different workers can put their boxes simultaneously. A worker i is less efficient than a worker j if either condition is met: leftToRighti + rightToLefti > leftToRightj + rightToLeftj leftToRighti + rightToLefti == leftToRightj + rightToLeftj and i > j The following rules regulate the movement of the workers through the bridge : If a worker x reaches the bridge while another worker y is crossing the bridge, x waits at their side of the bridge. If the bridge is free, the worker waiting on the right side of the bridge gets to cross the bridge. If more than one worker is waiting on the right side, the one with the lowest efficiency crosses first. If the bridge is free and no worker is waiting on the right side, and at least one box remains at the old warehouse, the worker on the left side of the river gets to cross the bridge. If more than one worker is waiting on the left side, the one with the lowest efficiency crosses first. Return the instance of time at which the last worker reaches the left bank of the river after all n boxes have been put in the new warehouse.   Example 1: Input: n = 1, k = 3, time = [[1,1,2,1],[1,1,3,1],[1,1,4,1]] Output: 6 Explanation: From 0 to 1: worker 2 crosses the bridge from the left bank to the right bank. From 1 to 2: worker 2 picks up a box from the old warehouse. From 2 to 6: worker 2 crosses the bridge from the right bank to the left bank. From 6 to 7: worker 2 puts a box at the new warehouse. The whole process ends after 7 minutes. We return 6 because the problem asks for the instance of time at which the last worker reaches the left bank. Example 2: Input: n = 3, k = 2, time = [[1,9,1,8],[10,10,10,10]] Output: 50 Explanation: From 0  to 10: worker 1 crosses the bridge from the left bank to the right bank. From 10 to 20: worker 1 picks up a box from the old warehouse. From 10 to 11: worker 0 crosses the bridge from the left bank to the right bank. From 11 to 20: worker 0 picks up a box from the old warehouse. From 20 to 30: worker 1 crosses the bridge from the right bank to the left bank. From 30 to 40: worker 1 puts a box at the new warehouse. From 30 to 31: worker 0 crosses the bridge from the right bank to the left bank. From 31 to 39: worker 0 puts a box at the new warehouse. From 39 to 40: worker 0 crosses the bridge from the left bank to the right bank. From 40 to 49: worker 0 picks up a box from the old warehouse. From 49 to 50: worker 0 crosses the bridge from the right bank to the left bank. From 50 to 58: worker 0 puts a box at the new warehouse. The whole process ends after 58 minutes. We return 50 because the problem asks for the instance of time at which the last worker reaches the left bank.   Constraints: 1 <= n, k <= 10000 time.length == k time[i].length == 4 1 <= leftToRighti, pickOldi, rightToLefti, putNewi <= 1000
class Solution: def findCrossingTime(self, n: int, k: int, time: List[List[int]]) -> int: left = [(-ltr - rtl, -i, 0) for i, (ltr, po, rtl, pn) in enumerate(time)] right = [] heapq.heapify(left) leftPick = [] rightPick = [] t = 0 toPick = n # kkk = 0 while n > 0: while leftPick and leftPick[0][0] <= t: nt, i, pri = heapq.heappop(leftPick) heapq.heappush(left, (pri, -i, nt)) while rightPick and rightPick[0][0] <= t: nt, i, pri = heapq.heappop(rightPick) heapq.heappush(right, (pri, -i, nt)) if right and right[0][2] <= t: pri, i, _ = heapq.heappop(right) i = -i t += time[i][2] heapq.heappush(leftPick, (t + time[i][3], i, pri)) n -= 1 elif toPick > 0 and left and left[0][2] <= t: pri, i, _ = heapq.heappop(left) i = -i t += time[i][0] heapq.heappush(rightPick, (t + time[i][1], i, pri)) toPick -= 1 if toPick == 0: left = [] else: tt = math.inf if leftPick and leftPick[0][0] > t: tt = min(tt, leftPick[0][0]) if rightPick and rightPick[0][0] > t: tt = min(tt, rightPick[0][0]) if left and left[0][2] > t: tt = min(tt, left[0][2]) if right and right[0][2] > t: tt = min(tt, right[0][2]) t = max(tt, t) # print(tt, t) # kkk += 1 # if kkk == 30: # print(right) # print(left) # print(leftPick) # print(rightPick) # print(toPick) # print(n) # break return t
d480cf
bf6a85
You are given an m x n binary grid grid where 1 represents land and 0 represents water. An island is a maximal 4-directionally (horizontal or vertical) connected group of 1's. The grid is said to be connected if we have exactly one island, otherwise is said disconnected. In one day, we are allowed to change any single land cell (1) into a water cell (0). Return the minimum number of days to disconnect the grid.   Example 1: Input: grid = [[0,1,1,0],[0,1,1,0],[0,0,0,0]] Output: 2 Explanation: We need at least 2 days to get a disconnected grid. Change land grid[1][1] and grid[0][2] to water and get 2 disconnected island. Example 2: Input: grid = [[1,1]] Output: 2 Explanation: Grid of full water is also disconnected ([[1,1]] -> [[0,0]]), 0 islands.   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 30 grid[i][j] is either 0 or 1.
class Solution: def minDays(self, grid: List[List[int]]) -> int: width,height = len(grid[0]),len(grid) def countislands(grid): islands = 0 seen = set() for row in range(height): for col in range(width): if (row,col) not in seen and grid[row][col] == 1: islands+=1 tocheck = [(row,col)] seen.add((row,col)) while len(tocheck)>0: newtocheck = set() for el in tocheck: compass = [(el[0]+1,el[1]),(el[0],el[1]+1),(el[0]-1,el[1]),(el[0],el[1]-1)] for d in compass: if d[0]>=0 and d[0]<height and d[1]>=0 and d[1]<width: if d not in seen and grid[d[0]][d[1]] == 1: newtocheck.add(d) seen.add(d) tocheck = newtocheck return islands if countislands(grid)>1: return 0 for row in range(len(grid)): for col in range(len(grid[row])): if grid[row][col] == 1: #print(row,col) clonegrid = copy.deepcopy(grid) clonegrid[row][col] = 0 if countislands(clonegrid)>1: #print("works!") return 1 return 2
b140fc
bf6a85
You are given an m x n binary grid grid where 1 represents land and 0 represents water. An island is a maximal 4-directionally (horizontal or vertical) connected group of 1's. The grid is said to be connected if we have exactly one island, otherwise is said disconnected. In one day, we are allowed to change any single land cell (1) into a water cell (0). Return the minimum number of days to disconnect the grid.   Example 1: Input: grid = [[0,1,1,0],[0,1,1,0],[0,0,0,0]] Output: 2 Explanation: We need at least 2 days to get a disconnected grid. Change land grid[1][1] and grid[0][2] to water and get 2 disconnected island. Example 2: Input: grid = [[1,1]] Output: 2 Explanation: Grid of full water is also disconnected ([[1,1]] -> [[0,0]]), 0 islands.   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 30 grid[i][j] is either 0 or 1.
class Solution(object): def minDays(self, grid): """ :type grid: List[List[int]] :rtype: int """ n, m = len(grid), len(grid[0]) def _components(): comps = 0 seen = set() for x in xrange(n): for y in xrange(m): if grid[x][y] == 0 or (x, y) in seen: continue comps += 1 q = set() q.add((x, y)) while q: seen.update(q) q = set((ii, jj) for i, j in q for ii, jj in ((i-1,j), (i+1,j), (i,j-1), (i,j+1)) if 0 <= ii < n and 0 <= jj < m and grid[ii][jj] and (ii,jj) not in seen) return comps if _components() != 1: return 0 for i in xrange(n): for j in xrange(m): if grid[i][j]: grid[i][j] = 0 if _components() != 1: return 1 grid[i][j] = 1 return 2
79d802
6d4708
You want to schedule a list of jobs in d days. Jobs are dependent (i.e To work on the ith job, you have to finish all the jobs j where 0 <= j < i). You have to finish at least one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the d days. The difficulty of a day is the maximum difficulty of a job done on that day. You are given an integer array jobDifficulty and an integer d. The difficulty of the ith job is jobDifficulty[i]. Return the minimum difficulty of a job schedule. If you cannot find a schedule for the jobs return -1.   Example 1: Input: jobDifficulty = [6,5,4,3,2,1], d = 2 Output: 7 Explanation: First day you can finish the first 5 jobs, total difficulty = 6. Second day you can finish the last job, total difficulty = 1. The difficulty of the schedule = 6 + 1 = 7 Example 2: Input: jobDifficulty = [9,9,9], d = 4 Output: -1 Explanation: If you finish a job per day you will still have a free day. you cannot find a schedule for the given jobs. Example 3: Input: jobDifficulty = [1,1,1], d = 3 Output: 3 Explanation: The schedule is one job per day. total difficulty will be 3.   Constraints: 1 <= jobDifficulty.length <= 300 0 <= jobDifficulty[i] <= 1000 1 <= d <= 10
from functools import lru_cache class Solution(object): def minDifficulty(self, A, D): """ :type jobDifficulty: List[int] :type d: int :rtype: int """ N = len(A) if D > N: return -1 # Split A into D subarrays to minimize sum( max(B) for B subarray) maxes = [[0] * N for _ in range(N)] for i in range(N): cur = A[i] for j in range(i, N): if A[j] > cur: cur = A[j] maxes[i][j] = cur @lru_cache(None) def dp(i, days): if days == 1: return maxes[i][-1] ans = float('inf') for j in range(i, N - days + 1): cand = maxes[i][j] + dp(j+1, days-1) if cand < ans: ans = cand return ans ans = dp(0, D) if ans == float('inf'): ans = -1 return ans
6e90c3
6d4708
You want to schedule a list of jobs in d days. Jobs are dependent (i.e To work on the ith job, you have to finish all the jobs j where 0 <= j < i). You have to finish at least one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the d days. The difficulty of a day is the maximum difficulty of a job done on that day. You are given an integer array jobDifficulty and an integer d. The difficulty of the ith job is jobDifficulty[i]. Return the minimum difficulty of a job schedule. If you cannot find a schedule for the jobs return -1.   Example 1: Input: jobDifficulty = [6,5,4,3,2,1], d = 2 Output: 7 Explanation: First day you can finish the first 5 jobs, total difficulty = 6. Second day you can finish the last job, total difficulty = 1. The difficulty of the schedule = 6 + 1 = 7 Example 2: Input: jobDifficulty = [9,9,9], d = 4 Output: -1 Explanation: If you finish a job per day you will still have a free day. you cannot find a schedule for the given jobs. Example 3: Input: jobDifficulty = [1,1,1], d = 3 Output: 3 Explanation: The schedule is one job per day. total difficulty will be 3.   Constraints: 1 <= jobDifficulty.length <= 300 0 <= jobDifficulty[i] <= 1000 1 <= d <= 10
class Solution(object): def minDifficulty(self, jobDifficulty, d): """ :type jobDifficulty: List[int] :type d: int :rtype: int """ t = jobDifficulty n = len(t) if n < d: return -1 f = [0] + [float('inf')]*n for _ in xrange(d): g = [float('inf')]*(n+1) for i in xrange(1, n+1): m = t[i-1] for j in xrange(i-1, -1, -1): m = max(m, t[j]) g[i] = min(g[i], f[j] + m) f = g return f[-1]
409805
00858b
A tree rooted at node 0 is given as follows: The number of nodes is nodes; The value of the ith node is value[i]; The parent of the ith node is parent[i]. Remove every subtree whose sum of values of nodes is zero. Return the number of the remaining nodes in the tree. Example 1: Input: nodes = 7, parent = [-1,0,0,1,2,2,2], value = [1,-2,4,0,-2,-1,-1] Output: 2 Example 2: Input: nodes = 7, parent = [-1,0,0,1,2,2,2], value = [1,-2,4,0,-2,-1,-2] Output: 6 Constraints: 1 <= nodes <= 10000 parent.length == nodes 0 <= parent[i] <= nodes - 1 parent[0] == -1 which indicates that 0 is the root. value.length == nodes -100000 <= value[i] <= 100000 The given input is guaranteed to represent a valid tree.
class Solution(object): def deleteTreeNodes(self, N, parent, value): """ :type nodes: int :type parent: List[int] :type value: List[int] :rtype: int """ children = [[] for _ in xrange(N)] for c, p in enumerate(parent): if p != -1: children[p].append(c) bad = [False] * N def dfs(node): # return subtree sum ans = value[node] for nei in children[node]: ans += dfs(nei) if ans == 0: bad[node] = True return ans dfs(0) self.ans = N def dfs2(node, b=False): if bad[node]: b = True if b is True: self.ans -= 1 for nei in children[node]: dfs2(nei, b) dfs2(0) return self.ans
21ea0f
00858b
A tree rooted at node 0 is given as follows: The number of nodes is nodes; The value of the ith node is value[i]; The parent of the ith node is parent[i]. Remove every subtree whose sum of values of nodes is zero. Return the number of the remaining nodes in the tree. Example 1: Input: nodes = 7, parent = [-1,0,0,1,2,2,2], value = [1,-2,4,0,-2,-1,-1] Output: 2 Example 2: Input: nodes = 7, parent = [-1,0,0,1,2,2,2], value = [1,-2,4,0,-2,-1,-2] Output: 6 Constraints: 1 <= nodes <= 10000 parent.length == nodes 0 <= parent[i] <= nodes - 1 parent[0] == -1 which indicates that 0 is the root. value.length == nodes -100000 <= value[i] <= 100000 The given input is guaranteed to represent a valid tree.
class Solution: def deleteTreeNodes(self, n: int, parent: List[int], value: List[int]) -> int: def search(x): nonlocal s tot = value[x] for i in c[x]: tot += search(i) s[x] = tot return tot def find(x): nonlocal ret if s[x] == 0: return ret += 1 for i in c[x]: find(i) c = [[] for i in range(n)] s = [0] * n for i, p in enumerate(parent): if p >= 0: c[p].append(i) search(0) ret = 0 find(0) return ret
685aca
780fa9
There is a broken calculator that has the integer startValue on its display initially. In one operation, you can: multiply the number on display by 2, or subtract 1 from the number on display. Given two integers startValue and target, return the minimum number of operations needed to display target on the calculator.   Example 1: Input: startValue = 2, target = 3 Output: 2 Explanation: Use double operation and then decrement operation {2 -> 4 -> 3}. Example 2: Input: startValue = 5, target = 8 Output: 2 Explanation: Use decrement and then double {5 -> 4 -> 8}. Example 3: Input: startValue = 3, target = 10 Output: 3 Explanation: Use double, decrement and double {3 -> 6 -> 5 -> 10}.   Constraints: 1 <= startValue, target <= 10^9
class Solution(object): def brokenCalc(self, X, Y): """ :type X: int :type Y: int :rtype: int """ ops = 0 while Y > X: if Y % 2 == 1: ops += 1 Y += 1 else: Y /= 2 ops += 1 return ops + X - Y
890d53
780fa9
There is a broken calculator that has the integer startValue on its display initially. In one operation, you can: multiply the number on display by 2, or subtract 1 from the number on display. Given two integers startValue and target, return the minimum number of operations needed to display target on the calculator.   Example 1: Input: startValue = 2, target = 3 Output: 2 Explanation: Use double operation and then decrement operation {2 -> 4 -> 3}. Example 2: Input: startValue = 5, target = 8 Output: 2 Explanation: Use decrement and then double {5 -> 4 -> 8}. Example 3: Input: startValue = 3, target = 10 Output: 3 Explanation: Use double, decrement and double {3 -> 6 -> 5 -> 10}.   Constraints: 1 <= startValue, target <= 10^9
class Solution: def brokenCalc(self, X: 'int', Y: 'int') -> 'int': ans = 0 while Y > X: if Y & 1: Y += 1 ans += 1 else: Y >>= 1 ans += 1 ans += X - Y return ans
6dc854
22dfe7
You are given a 0-indexed binary string s of length n on which you can apply two types of operations: Choose an index i and invert all characters from index 0 to index i (both inclusive), with a cost of i + 1 Choose an index i and invert all characters from index i to index n - 1 (both inclusive), with a cost of n - i Return the minimum cost to make all characters of the string equal. Invert a character means if its value is '0' it becomes '1' and vice-versa.   Example 1: Input: s = "0011" Output: 2 Explanation: Apply the second operation with i = 2 to obtain s = "0000" for a cost of 2. It can be shown that 2 is the minimum cost to make all characters equal. Example 2: Input: s = "010101" Output: 9 Explanation: Apply the first operation with i = 2 to obtain s = "101101" for a cost of 3. Apply the first operation with i = 1 to obtain s = "011101" for a cost of 2. Apply the first operation with i = 0 to obtain s = "111101" for a cost of 1. Apply the second operation with i = 4 to obtain s = "111110" for a cost of 2. Apply the second operation with i = 5 to obtain s = "111111" for a cost of 1. The total cost to make all characters equal is 9. It can be shown that 9 is the minimum cost to make all characters equal.   Constraints: 1 <= s.length == n <= 105 s[i] is either '0' or '1'
class Solution(object): def minimumCost(self, s): """ :type s: str :rtype: int """ a = 0 for i in range(1, len(s)): a += 0 if s[i - 1] == s[i] else min(i, len(s) - i) return a
58a45a
22dfe7
You are given a 0-indexed binary string s of length n on which you can apply two types of operations: Choose an index i and invert all characters from index 0 to index i (both inclusive), with a cost of i + 1 Choose an index i and invert all characters from index i to index n - 1 (both inclusive), with a cost of n - i Return the minimum cost to make all characters of the string equal. Invert a character means if its value is '0' it becomes '1' and vice-versa.   Example 1: Input: s = "0011" Output: 2 Explanation: Apply the second operation with i = 2 to obtain s = "0000" for a cost of 2. It can be shown that 2 is the minimum cost to make all characters equal. Example 2: Input: s = "010101" Output: 9 Explanation: Apply the first operation with i = 2 to obtain s = "101101" for a cost of 3. Apply the first operation with i = 1 to obtain s = "011101" for a cost of 2. Apply the first operation with i = 0 to obtain s = "111101" for a cost of 1. Apply the second operation with i = 4 to obtain s = "111110" for a cost of 2. Apply the second operation with i = 5 to obtain s = "111111" for a cost of 1. The total cost to make all characters equal is 9. It can be shown that 9 is the minimum cost to make all characters equal.   Constraints: 1 <= s.length == n <= 105 s[i] is either '0' or '1'
class Solution: def minimumCost(self, s: str) -> int: ans = 0 for i in range(1, len(s)): if s[i - 1] != s[i]: ans += min(i, len(s) - i) return ans
14975e
176e0d
You have two fruit baskets containing n fruits each. You are given two 0-indexed integer arrays basket1 and basket2 representing the cost of fruit in each basket. You want to make both baskets equal. To do so, you can use the following operation as many times as you want: Chose two indices i and j, and swap the ith fruit of basket1 with the jth fruit of basket2. The cost of the swap is min(basket1[i],basket2[j]). Two baskets are considered equal if sorting them according to the fruit cost makes them exactly the same baskets. Return the minimum cost to make both the baskets equal or -1 if impossible.   Example 1: Input: basket1 = [4,2,2,2], basket2 = [1,4,1,2] Output: 1 Explanation: Swap index 1 of basket1 with index 0 of basket2, which has cost 1. Now basket1 = [4,1,2,2] and basket2 = [2,4,1,2]. Rearranging both the arrays makes them equal. Example 2: Input: basket1 = [2,3,4,1], basket2 = [3,2,5,1] Output: -1 Explanation: It can be shown that it is impossible to make both the baskets equal.   Constraints: basket1.length == bakste2.length 1 <= basket1.length <= 100000 1 <= basket1[i],basket2[i] <= 10^9
class Solution(object): def minCost(self, basket1, basket2): """ :type basket1: List[int] :type basket2: List[int] :rtype: int """ m, h, l, n, a = min(min(basket1), min(basket2)), defaultdict(int), [], [], 0 for i in range(len(basket1)): h[basket1[i]] += 1 h[basket2[i]] -= 1 for i in h.keys(): if h[i] % 2 == 1: return -1 if h[i] > 0: for j in range(h[i] / 2): l.append(i) elif h[i] < 0: for j in range(abs(h[i]) / 2): n.append(i) l.sort() n.sort() for i in range(len(l)): a += min(2 * m, min(l[i], n[-i - 1])) return a
7d1a55
176e0d
You have two fruit baskets containing n fruits each. You are given two 0-indexed integer arrays basket1 and basket2 representing the cost of fruit in each basket. You want to make both baskets equal. To do so, you can use the following operation as many times as you want: Chose two indices i and j, and swap the ith fruit of basket1 with the jth fruit of basket2. The cost of the swap is min(basket1[i],basket2[j]). Two baskets are considered equal if sorting them according to the fruit cost makes them exactly the same baskets. Return the minimum cost to make both the baskets equal or -1 if impossible.   Example 1: Input: basket1 = [4,2,2,2], basket2 = [1,4,1,2] Output: 1 Explanation: Swap index 1 of basket1 with index 0 of basket2, which has cost 1. Now basket1 = [4,1,2,2] and basket2 = [2,4,1,2]. Rearranging both the arrays makes them equal. Example 2: Input: basket1 = [2,3,4,1], basket2 = [3,2,5,1] Output: -1 Explanation: It can be shown that it is impossible to make both the baskets equal.   Constraints: basket1.length == bakste2.length 1 <= basket1.length <= 100000 1 <= basket1[i],basket2[i] <= 10^9
class Solution: def minCost(self, basket1: List[int], basket2: List[int]) -> int: ctall = collections.Counter(basket1) + collections.Counter(basket2) for k in ctall.values() : if not k % 2 == 0 : return -1 ct1 = collections.Counter(basket1) # to_in, to_out = [], [] # for k in ct1 : # v1, ve = ct1[k], ctall[k] // 2 # if v1 > ve : # to_out += [k]*(v1-ve) # if v1 < ve : # to_in += [k]*(ve-v1) minv = min(ctall) print(ct1) print(ctall) to_deal = [] for k in ctall : v1, ve = ct1[k], ctall[k] // 2 to_deal += [k]*abs(v1-ve) to_deal = sorted(to_deal)[:len(to_deal)//2] to_ret = sum([min(t, minv*2) for t in to_deal]) return to_ret
e867e7
4dbf65
The alternating sum of a 0-indexed array is defined as the sum of the elements at even indices minus the sum of the elements at odd indices. For example, the alternating sum of [4,2,5,3] is (4 + 5) - (2 + 3) = 4. Given an array nums, return the maximum alternating sum of any subsequence of nums (after reindexing the elements of the subsequence). A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the underlined elements), while [2,4,2] is not.   Example 1: Input: nums = [4,2,5,3] Output: 7 Explanation: It is optimal to choose the subsequence [4,2,5] with alternating sum (4 + 5) - 2 = 7. Example 2: Input: nums = [5,6,7,8] Output: 8 Explanation: It is optimal to choose the subsequence [8] with alternating sum 8. Example 3: Input: nums = [6,2,1,2,4,5] Output: 10 Explanation: It is optimal to choose the subsequence [6,1,5] with alternating sum (6 + 5) - 1 = 10.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 100000
class Solution: def maxAlternatingSum(self, nums: List[int]) -> int: @functools.lru_cache(maxsize=None) def dp(i: int, odd: True): if i == len(nums): return 0 if odd: return max(dp(i + 1, True), dp(i + 1, False) - nums[i]) else: return max(dp(i + 1, False), dp(i + 1, True) + nums[i]) for i in range(len(nums), 0, -1): dp(i, True) dp(i, False) answer = dp(0, False) dp.cache_clear() return answer
433d6c
4dbf65
The alternating sum of a 0-indexed array is defined as the sum of the elements at even indices minus the sum of the elements at odd indices. For example, the alternating sum of [4,2,5,3] is (4 + 5) - (2 + 3) = 4. Given an array nums, return the maximum alternating sum of any subsequence of nums (after reindexing the elements of the subsequence). A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the underlined elements), while [2,4,2] is not.   Example 1: Input: nums = [4,2,5,3] Output: 7 Explanation: It is optimal to choose the subsequence [4,2,5] with alternating sum (4 + 5) - 2 = 7. Example 2: Input: nums = [5,6,7,8] Output: 8 Explanation: It is optimal to choose the subsequence [8] with alternating sum 8. Example 3: Input: nums = [6,2,1,2,4,5] Output: 10 Explanation: It is optimal to choose the subsequence [6,1,5] with alternating sum (6 + 5) - 1 = 10.   Constraints: 1 <= nums.length <= 100000 1 <= nums[i] <= 100000
class Solution(object): def maxAlternatingSum(self, A): dp = [0, -float('inf')] for a in A: dp = [max(dp[0], dp[1] - a), max(dp[1], dp[0] + a)] return max(dp)
8e71f8
6a8362
Given n orders, each order consist in pickup and delivery services.  Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i).  Since the answer may be too large, return it modulo 10^9 + 7.   Example 1: Input: n = 1 Output: 1 Explanation: Unique order (P1, D1), Delivery 1 always is after of Pickup 1. Example 2: Input: n = 2 Output: 6 Explanation: All possible orders: (P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1). This is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2. Example 3: Input: n = 3 Output: 90   Constraints: 1 <= n <= 500
class Solution(object): def countOrders(self, n): """ :type n: int :rtype: int """ ans = 1 mod = 10 ** 9 + 7 for i in xrange(1, n * 2 + 1): ans = ans * i % mod for i in xrange(n): ans = ans * 500000004 % mod return ans
0fa952
6a8362
Given n orders, each order consist in pickup and delivery services.  Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i).  Since the answer may be too large, return it modulo 10^9 + 7.   Example 1: Input: n = 1 Output: 1 Explanation: Unique order (P1, D1), Delivery 1 always is after of Pickup 1. Example 2: Input: n = 2 Output: 6 Explanation: All possible orders: (P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1). This is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2. Example 3: Input: n = 3 Output: 90   Constraints: 1 <= n <= 500
class Solution: def countOrders(self, n: int) -> int: mod = 10 ** 9 + 7 nf = 1 n2 = 1 for i in range(1, n + 1): n2 = (n2 * 2) # % mod nf = (nf * (2 * i) * (2 * i - 1)) # % mod return (nf // n2) % mod
5af747
b5f2a8
You are given the root of a binary tree and an integer distance. A pair of two different leaf nodes of a binary tree is said to be good if the length of the shortest path between them is less than or equal to distance. Return the number of good leaf node pairs in the tree.   Example 1: Input: root = [1,2,3,null,4], distance = 3 Output: 1 Explanation: The leaf nodes of the tree are 3 and 4 and the length of the shortest path between them is 3. This is the only good pair. Example 2: Input: root = [1,2,3,4,5,6,7], distance = 3 Output: 2 Explanation: The good pairs are [4,5] and [6,7] with shortest path = 2. The pair [4,6] is not good because the length of ther shortest path between them is 4. Example 3: Input: root = [7,1,4,6,null,5,3,null,null,null,null,null,2], distance = 3 Output: 1 Explanation: The only good pair is [2,5].   Constraints: The number of nodes in the tree is in the range [1, 210]. 1 <= Node.val <= 100 1 <= distance <= 10
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def countPairs(self, root, distance): graph = collections.defaultdict(list) M = {} nodes = [] leaves = set() self.t = 0 def dfs(node): if node: M[node] = ans = self.t self.t += 1 v1 = dfs(node.left) v2 = dfs(node.right) if v1 is not None: graph[ans].append(v1) graph[v1].append(ans) if v2 is not None: graph[ans].append(v2) graph[v2].append(ans) if v1 is v2 is None: leaves.add(ans) return ans dfs(root) Minv = [0] * len(M) for node in M: i = M[node] Minv[i] = node #print("!", leaves, graph) ans = 0 for i in leaves: rooty = i queue = [[i, 0]] seen = {i} for node, d in queue: if d > distance: break if node in leaves and node != rooty: #print("!", node, d) ans += 1 for nei in graph[node]: if nei not in seen: seen.add(nei) queue.append([nei, d + 1]) return ans // 2
b33580
b5f2a8
You are given the root of a binary tree and an integer distance. A pair of two different leaf nodes of a binary tree is said to be good if the length of the shortest path between them is less than or equal to distance. Return the number of good leaf node pairs in the tree.   Example 1: Input: root = [1,2,3,null,4], distance = 3 Output: 1 Explanation: The leaf nodes of the tree are 3 and 4 and the length of the shortest path between them is 3. This is the only good pair. Example 2: Input: root = [1,2,3,4,5,6,7], distance = 3 Output: 2 Explanation: The good pairs are [4,5] and [6,7] with shortest path = 2. The pair [4,6] is not good because the length of ther shortest path between them is 4. Example 3: Input: root = [7,1,4,6,null,5,3,null,null,null,null,null,2], distance = 3 Output: 1 Explanation: The only good pair is [2,5].   Constraints: The number of nodes in the tree is in the range [1, 210]. 1 <= Node.val <= 100 1 <= distance <= 10
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def dfs(self, root, depth): if not root: return [] if not root.left and not root.right: return [depth] l = self.dfs(root.left, depth + 1) r = self.dfs(root.right, depth + 1) ans = [i for i in itertools.chain(l, r) if i - depth < self.distance] for i in l: if i - depth < self.distance: for j in r: if j + i - depth - depth <= self.distance: self.ans += 1 return ans def countPairs(self, root: TreeNode, distance: int) -> int: self.ans = 0 self.distance = distance self.dfs(root, 0) return self.ans
a2e8be
fbbbee
Given a string s, return the number of different non-empty palindromic subsequences in s. Since the answer may be very large, return it modulo 10^9 + 7. A subsequence of a string is obtained by deleting zero or more characters from the string. A sequence is palindromic if it is equal to the sequence reversed. Two sequences a1, a2, ... and b1, b2, ... are different if there is some i for which ai != bi.   Example 1: Input: s = "bccb" Output: 6 Explanation: The 6 different non-empty palindromic subsequences are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'. Note that 'bcb' is counted only once, even though it occurs twice. Example 2: Input: s = "abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba" Output: 104860361 Explanation: There are 3104860382 different non-empty palindromic subsequences, which is 104860361 modulo 10^9 + 7.   Constraints: 1 <= s.length <= 1000 s[i] is either 'a', 'b', 'c', or 'd'.
class Solution(object): def countPalindromicSubsequences(self, S): """ :type S: str :rtype: int """ n = len(S) prime = (10**9) + 7 vocab = list(set(S)) mem = dict() def search(x, y): res = mem.get((x, y), None) if res is not None: return res res = 1 for nxt in vocab: a = S.find(nxt, x) if a == -1: continue b = S.rfind(nxt, x, y+1) if b == -1: continue if a == b: res = (res + 1) % prime elif a < b: res = (res + search(a+1, b-1) + 1) % prime mem[(x,y)] = res return res return (search(0, n-1) - 1) % prime
8d7780
fbbbee
Given a string s, return the number of different non-empty palindromic subsequences in s. Since the answer may be very large, return it modulo 10^9 + 7. A subsequence of a string is obtained by deleting zero or more characters from the string. A sequence is palindromic if it is equal to the sequence reversed. Two sequences a1, a2, ... and b1, b2, ... are different if there is some i for which ai != bi.   Example 1: Input: s = "bccb" Output: 6 Explanation: The 6 different non-empty palindromic subsequences are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'. Note that 'bcb' is counted only once, even though it occurs twice. Example 2: Input: s = "abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba" Output: 104860361 Explanation: There are 3104860382 different non-empty palindromic subsequences, which is 104860361 modulo 10^9 + 7.   Constraints: 1 <= s.length <= 1000 s[i] is either 'a', 'b', 'c', or 'd'.
import sys class Solution: MOD = 10**9 + 7 def count(self, S, left, right): if (left, right) in self.result: return self.result[(left, right)] r = 0 for ch in ('a', 'b', 'c', 'd'): first_ch = self.first[left].get(ch) last_ch = self.last[right].get(ch) if first_ch is None or first_ch > right: continue if last_ch is None or last_ch < left: continue # Single character r += 1 if r >= self.MOD: r -= self.MOD if first_ch != last_ch: # Double character r += 1 if r >= self.MOD: r -= self.MOD # Contain sub = self.count(S, first_ch+1, last_ch-1) r += sub if r >= self.MOD: r -= self.MOD self.result[(left, right)] = r return r def countPalindromicSubsequences(self, S): """ :type S: str :rtype: int """ N = len(S) self.first = [] for i in range(N): first = {} for j in range(i, N): if S[j] not in first: first[S[j]] = j self.first.append(first) self.last = [] for i in range(N): last = {} for j in range(i, -1, -1): if S[j] not in last: last[S[j]] = j self.last.append(last) self.result = {} for i in range(0, N): self.result[(i+1, i)] = 0 return self.count(S, 0, N-1)
7ba94f
e9b0e6
Suppose LeetCode will start its IPO soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the IPO. Since it has limited resources, it can only finish at most k distinct projects before the IPO. Help LeetCode design the best way to maximize its total capital after finishing at most k distinct projects. You are given n projects where the ith project has a pure profit profits[i] and a minimum capital of capital[i] is needed to start it. Initially, you have w capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital. Pick a list of at most k distinct projects from given projects to maximize your final capital, and return the final maximized capital. The answer is guaranteed to fit in a 32-bit signed integer.   Example 1: Input: k = 2, w = 0, profits = [1,2,3], capital = [0,1,1] Output: 4 Explanation: Since your initial capital is 0, you can only start the project indexed 0. After finishing it you will obtain profit 1 and your capital becomes 1. With capital 1, you can either start the project indexed 1 or the project indexed 2. Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital. Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4. Example 2: Input: k = 3, w = 0, profits = [1,2,3], capital = [0,1,2] Output: 6   Constraints: 1 <= k <= 100000 0 <= w <= 10^9 n == profits.length n == capital.length 1 <= n <= 100000 0 <= profits[i] <= 10000 0 <= capital[i] <= 10^9
class Solution(object): def findMaximizedCapital(self, k, W, Profits, Capital): """ :type k: int :type W: int :type Profits: List[int] :type Capital: List[int] :rtype: int """ import heapq h = [] l = len(Profits) new = [] for i in range(l): new.append((Capital[i], Profits[i])) new.sort(reverse=True) result = W while new and new[-1][0] <= result: c,p = new.pop() heapq.heappush(h, -p) i = 0 while i < k and h: result -= heapq.heappop(h) while new and new[-1][0] <= result: c,p = new.pop() heapq.heappush(h,-p) i += 1 return result
b23f34
30e5fe
You are given an integer n. There are n rooms numbered from 0 to n - 1. You are given a 2D integer array meetings where meetings[i] = [starti, endi] means that a meeting will be held during the half-closed time interval [starti, endi). All the values of starti are unique. Meetings are allocated to rooms in the following manner: Each meeting will take place in the unused room with the lowest number. If there are no available rooms, the meeting will be delayed until a room becomes free. The delayed meeting should have the same duration as the original meeting. When a room becomes unused, meetings that have an earlier original start time should be given the room. Return the number of the room that held the most meetings. If there are multiple rooms, return the room with the lowest number. A half-closed interval [a, b) is the interval between a and b including a and not including b.   Example 1: Input: n = 2, meetings = [[0,10],[1,5],[2,7],[3,4]] Output: 0 Explanation: - At time 0, both rooms are not being used. The first meeting starts in room 0. - At time 1, only room 1 is not being used. The second meeting starts in room 1. - At time 2, both rooms are being used. The third meeting is delayed. - At time 3, both rooms are being used. The fourth meeting is delayed. - At time 5, the meeting in room 1 finishes. The third meeting starts in room 1 for the time period [5,10). - At time 10, the meetings in both rooms finish. The fourth meeting starts in room 0 for the time period [10,11). Both rooms 0 and 1 held 2 meetings, so we return 0. Example 2: Input: n = 3, meetings = [[1,20],[2,10],[3,5],[4,9],[6,8]] Output: 1 Explanation: - At time 1, all three rooms are not being used. The first meeting starts in room 0. - At time 2, rooms 1 and 2 are not being used. The second meeting starts in room 1. - At time 3, only room 2 is not being used. The third meeting starts in room 2. - At time 4, all three rooms are being used. The fourth meeting is delayed. - At time 5, the meeting in room 2 finishes. The fourth meeting starts in room 2 for the time period [5,10). - At time 6, all three rooms are being used. The fifth meeting is delayed. - At time 10, the meetings in rooms 1 and 2 finish. The fifth meeting starts in room 1 for the time period [10,12). Room 0 held 1 meeting while rooms 1 and 2 each held 2 meetings, so we return 1.   Constraints: 1 <= n <= 100 1 <= meetings.length <= 100000 meetings[i].length == 2 0 <= starti < endi <= 5 * 100000 All the values of starti are unique.
class Solution: def mostBooked(self, n: int, meetings: List[List[int]]) -> int: meetings = sorted(meetings) m = len(meetings) times = [0] * n nums = [0] * n for i in range(m): idx = -1 vmin = inf flag = True for j in range(n): if times[j] <= meetings[i][0]: times[j] = meetings[i][1] nums[j] += 1 flag = False break else: if times[j] < vmin: idx = j vmin = times[j] if flag: times[idx] += meetings[i][1] - meetings[i][0] nums[idx] += 1 idx = -1 vmax = -1 for j in range(n): if nums[j] > vmax: idx = j vmax = nums[j] return idx
fcb1da
30e5fe
You are given an integer n. There are n rooms numbered from 0 to n - 1. You are given a 2D integer array meetings where meetings[i] = [starti, endi] means that a meeting will be held during the half-closed time interval [starti, endi). All the values of starti are unique. Meetings are allocated to rooms in the following manner: Each meeting will take place in the unused room with the lowest number. If there are no available rooms, the meeting will be delayed until a room becomes free. The delayed meeting should have the same duration as the original meeting. When a room becomes unused, meetings that have an earlier original start time should be given the room. Return the number of the room that held the most meetings. If there are multiple rooms, return the room with the lowest number. A half-closed interval [a, b) is the interval between a and b including a and not including b.   Example 1: Input: n = 2, meetings = [[0,10],[1,5],[2,7],[3,4]] Output: 0 Explanation: - At time 0, both rooms are not being used. The first meeting starts in room 0. - At time 1, only room 1 is not being used. The second meeting starts in room 1. - At time 2, both rooms are being used. The third meeting is delayed. - At time 3, both rooms are being used. The fourth meeting is delayed. - At time 5, the meeting in room 1 finishes. The third meeting starts in room 1 for the time period [5,10). - At time 10, the meetings in both rooms finish. The fourth meeting starts in room 0 for the time period [10,11). Both rooms 0 and 1 held 2 meetings, so we return 0. Example 2: Input: n = 3, meetings = [[1,20],[2,10],[3,5],[4,9],[6,8]] Output: 1 Explanation: - At time 1, all three rooms are not being used. The first meeting starts in room 0. - At time 2, rooms 1 and 2 are not being used. The second meeting starts in room 1. - At time 3, only room 2 is not being used. The third meeting starts in room 2. - At time 4, all three rooms are being used. The fourth meeting is delayed. - At time 5, the meeting in room 2 finishes. The fourth meeting starts in room 2 for the time period [5,10). - At time 6, all three rooms are being used. The fifth meeting is delayed. - At time 10, the meetings in rooms 1 and 2 finish. The fifth meeting starts in room 1 for the time period [10,12). Room 0 held 1 meeting while rooms 1 and 2 each held 2 meetings, so we return 1.   Constraints: 1 <= n <= 100 1 <= meetings.length <= 100000 meetings[i].length == 2 0 <= starti < endi <= 5 * 100000 All the values of starti are unique.
class Solution(object): def mostBooked(self, n, meetings): """ :type n: int :type meetings: List[List[int]] :rtype: int """ cs = [0]*n h = [] for i in range(n): heappush(h, (0, i)) mm = sorted(meetings) for s, e in mm: while h: t, i = h[0] if t>=s: break heappop(h) heappush(h, (s, i)) t, i = heappop(h) d = e-s cs[i]+=1 # print s, e, i, t, t+d heappush(h, (t+d, i)) ri = 0 for i in range(1, n): if cs[i]>cs[ri]: ri=i return ri
679878
72d33e
A string is a valid parentheses string (denoted VPS) if and only if it consists of "(" and ")" characters only, and: It is the empty string, or It can be written as AB (A concatenated with B), where A and B are VPS's, or It can be written as (A), where A is a VPS. We can similarly define the nesting depth depth(S) of any VPS S as follows: depth("") = 0 depth(A + B) = max(depth(A), depth(B)), where A and B are VPS's depth("(" + A + ")") = 1 + depth(A), where A is a VPS. For example,  "", "()()", and "()(()())" are VPS's (with nesting depths 0, 1, and 2), and ")(" and "(()" are not VPS's.   Given a VPS seq, split it into two disjoint subsequences A and B, such that A and B are VPS's (and A.length + B.length = seq.length). Now choose any such A and B such that max(depth(A), depth(B)) is the minimum possible value. Return an answer array (of length seq.length) that encodes such a choice of A and B:  answer[i] = 0 if seq[i] is part of A, else answer[i] = 1.  Note that even though multiple answers may exist, you may return any of them.   Example 1: Input: seq = "(()())" Output: [0,1,1,1,1,0] Example 2: Input: seq = "()(())()" Output: [0,0,0,1,1,0,1,1]   Constraints: 1 <= seq.size <= 10000
class Solution: def maxDepthAfterSplit(self, seq: str) -> List[int]: a = 0 b = 0 n = len(seq) ans = [0] * n for i, c in enumerate(seq): if c == '(': if a < b: a += 1 ans[i] = 0 else: b += 1 ans[i] = 1 else: if a < b: b -= 1 ans[i] = 1 else: a -= 1 ans[i] = 0 return ans
937c96
72d33e
A string is a valid parentheses string (denoted VPS) if and only if it consists of "(" and ")" characters only, and: It is the empty string, or It can be written as AB (A concatenated with B), where A and B are VPS's, or It can be written as (A), where A is a VPS. We can similarly define the nesting depth depth(S) of any VPS S as follows: depth("") = 0 depth(A + B) = max(depth(A), depth(B)), where A and B are VPS's depth("(" + A + ")") = 1 + depth(A), where A is a VPS. For example,  "", "()()", and "()(()())" are VPS's (with nesting depths 0, 1, and 2), and ")(" and "(()" are not VPS's.   Given a VPS seq, split it into two disjoint subsequences A and B, such that A and B are VPS's (and A.length + B.length = seq.length). Now choose any such A and B such that max(depth(A), depth(B)) is the minimum possible value. Return an answer array (of length seq.length) that encodes such a choice of A and B:  answer[i] = 0 if seq[i] is part of A, else answer[i] = 1.  Note that even though multiple answers may exist, you may return any of them.   Example 1: Input: seq = "(()())" Output: [0,1,1,1,1,0] Example 2: Input: seq = "()(())()" Output: [0,0,0,1,1,0,1,1]   Constraints: 1 <= seq.size <= 10000
class Solution(object): def maxDepthAfterSplit(self, seq): """ :type seq: str :rtype: List[int] """ # compute depth d = h = 0 for c in seq: if c == ')': h -= 1 if c == '(': h += 1 d = max(d, h) # cut depth in half d >>= 1 r = [0 for _ in seq] for i, c in enumerate(seq): if c == ')': h -= 1 if h >= d: r[i] = 1 if c == '(': h += 1 return r
ca67e7
881014
Given an array of integers arr and an integer d. In one step you can jump from index i to index: i + x where: i + x < arr.length and 0 < x <= d. i - x where: i - x >= 0 and 0 < x <= d. In addition, you can only jump from index i to index j if arr[i] > arr[j] and arr[i] > arr[k] for all indices k between i and j (More formally min(i, j) < k < max(i, j)). You can choose any index of the array and start jumping. Return the maximum number of indices you can visit. Notice that you can not jump outside of the array at any time.   Example 1: Input: arr = [6,4,14,6,8,13,9,7,10,6,12], d = 2 Output: 4 Explanation: You can start at index 10. You can jump 10 --> 8 --> 6 --> 7 as shown. Note that if you start at index 6 you can only jump to index 7. You cannot jump to index 5 because 13 > 9. You cannot jump to index 4 because index 5 is between index 4 and 6 and 13 > 9. Similarly You cannot jump from index 3 to index 2 or index 1. Example 2: Input: arr = [3,3,3,3,3], d = 3 Output: 1 Explanation: You can start at any index. You always cannot jump to any index. Example 3: Input: arr = [7,6,5,4,3,2,1], d = 1 Output: 7 Explanation: Start at index 0. You can visit all the indicies.   Constraints: 1 <= arr.length <= 1000 1 <= arr[i] <= 100000 1 <= d <= arr.length
class Solution(object): def maxJumps(self, A, D): """ :type arr: List[int] :type d: int :rtype: int """ ans = 0 N = n = len(A) # from i, can jump to [i-d, i+d] # on path from i -> j must not have any array element bigger vals = [(v, i) for i,v in enumerate(A)] vals.sort() maxes = [[0] * n for _ in range(n)] for i in range(n): m = A[i] for j in range(i, n): if A[j] > m: m = A[j] maxes[i][j] = m dp = [1] * n seen = set() for v, i in vals: for j in seen: if dp[j] + 1 <= dp[i]: continue if A[j] >= A[i]: continue if abs(i-j) > D: continue lo = min(i,j) hi = max(i,j) if i == lo: lo += 1 else: hi -= 1 if maxes[lo][hi] < A[i]: # can jump to j dp[i] = dp[j] + 1 seen.add(i) return max(dp)
bd71b3
881014
Given an array of integers arr and an integer d. In one step you can jump from index i to index: i + x where: i + x < arr.length and 0 < x <= d. i - x where: i - x >= 0 and 0 < x <= d. In addition, you can only jump from index i to index j if arr[i] > arr[j] and arr[i] > arr[k] for all indices k between i and j (More formally min(i, j) < k < max(i, j)). You can choose any index of the array and start jumping. Return the maximum number of indices you can visit. Notice that you can not jump outside of the array at any time.   Example 1: Input: arr = [6,4,14,6,8,13,9,7,10,6,12], d = 2 Output: 4 Explanation: You can start at index 10. You can jump 10 --> 8 --> 6 --> 7 as shown. Note that if you start at index 6 you can only jump to index 7. You cannot jump to index 5 because 13 > 9. You cannot jump to index 4 because index 5 is between index 4 and 6 and 13 > 9. Similarly You cannot jump from index 3 to index 2 or index 1. Example 2: Input: arr = [3,3,3,3,3], d = 3 Output: 1 Explanation: You can start at any index. You always cannot jump to any index. Example 3: Input: arr = [7,6,5,4,3,2,1], d = 1 Output: 7 Explanation: Start at index 0. You can visit all the indicies.   Constraints: 1 <= arr.length <= 1000 1 <= arr[i] <= 100000 1 <= d <= arr.length
class Solution: def maxJumps(self, arr: List[int], d: int) -> int: def s(x): if dp[x] is not None: return dp[x] dp[x] = 1 for j in range(x - 1, max(0, x - d) - 1, -1): if arr[j] >= arr[x]: break dp[x] = max(dp[x], 1 + s(j)) for j in range(x + 1, min(n - 1, x + d) + 1): if arr[j] >= arr[x]: break dp[x] = max(dp[x], 1 + s(j)) return dp[x] n = len(arr) dp = [None] * n for i in range(n): s(i) return max(dp)
0d8c7c
f49f4f
Given an integer array nums with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array. Implement the Solution class: Solution(int[] nums) Initializes the object with the array nums. int pick(int target) Picks a random index i from nums where nums[i] == target. If there are multiple valid i's, then each index should have an equal probability of returning.   Example 1: Input ["Solution", "pick", "pick", "pick"] [[[1, 2, 3, 3, 3]], [3], [1], [3]] Output [null, 4, 0, 2] Explanation Solution solution = new Solution([1, 2, 3, 3, 3]); solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning. solution.pick(1); // It should return 0. Since in the array only nums[0] is equal to 1. solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.   Constraints: 1 <= nums.length <= 2 * 10000 -2^31 <= nums[i] <= 2^31 - 1 target is an integer from nums. At most 10000 calls will be made to pick.
class Solution(object): def __init__(self, nums): """ :type nums: List[int] :type numsSize: int """ self.c = collections.Counter(nums) self.nums = nums def pick(self, target): """ :type target: int :rtype: int """ q = 0 c = self.c[target] n = random.randint(1, c) for i in range(len(self.nums)): if self.nums[i] == target: q += 1 if q == n: return i
cf71fb
db3683
A string is beautiful if: It consists of the first k letters of the English lowercase alphabet. It does not contain any substring of length 2 or more which is a palindrome. You are given a beautiful string s of length n and a positive integer k. Return the lexicographically smallest string of length n, which is larger than s and is beautiful. If there is no such string, return an empty string. A string a is lexicographically larger than a string b (of the same length) if in the first position where a and b differ, a has a character strictly larger than the corresponding character in b. For example, "abcd" is lexicographically larger than "abcc" because the first position they differ is at the fourth character, and d is greater than c.   Example 1: Input: s = "abcz", k = 26 Output: "abda" Explanation: The string "abda" is beautiful and lexicographically larger than the string "abcz". It can be proven that there is no string that is lexicographically larger than the string "abcz", beautiful, and lexicographically smaller than the string "abda". Example 2: Input: s = "dc", k = 4 Output: "" Explanation: It can be proven that there is no string that is lexicographically larger than the string "dc" and is beautiful.   Constraints: 1 <= n == s.length <= 10^5 4 <= k <= 26 s is a beautiful string.
class Solution(object): def smallestBeautifulString(self, s, k): """ :type s: str :type k: int :rtype: str """ s, i = list(s), len(s) - 1 s[i] = chr(ord(s[i]) + 1) while i >= 0 and i < len(s): if ord(s[i]) >= ord('a') + k: s[i], i = 'a', i - 1 if i >= 0: s[i] = chr(ord(s[i]) + 1) else: break elif i - 1 >= 0 and s[i] == s[i - 1] or i - 2 >= 0 and s[i] == s[i - 2]: s[i] = chr(ord(s[i]) + 1) else: i += 1 return "" if i == -1 else ''.join(s)
92470e
db3683
A string is beautiful if: It consists of the first k letters of the English lowercase alphabet. It does not contain any substring of length 2 or more which is a palindrome. You are given a beautiful string s of length n and a positive integer k. Return the lexicographically smallest string of length n, which is larger than s and is beautiful. If there is no such string, return an empty string. A string a is lexicographically larger than a string b (of the same length) if in the first position where a and b differ, a has a character strictly larger than the corresponding character in b. For example, "abcd" is lexicographically larger than "abcc" because the first position they differ is at the fourth character, and d is greater than c.   Example 1: Input: s = "abcz", k = 26 Output: "abda" Explanation: The string "abda" is beautiful and lexicographically larger than the string "abcz". It can be proven that there is no string that is lexicographically larger than the string "abcz", beautiful, and lexicographically smaller than the string "abda". Example 2: Input: s = "dc", k = 4 Output: "" Explanation: It can be proven that there is no string that is lexicographically larger than the string "dc" and is beautiful.   Constraints: 1 <= n == s.length <= 10^5 4 <= k <= 26 s is a beautiful string.
class Solution: def smallestBeautifulString(self, s: str, k: int) -> str: n = len(s) i = n - 1 ords = [ord(x) - ord("a") for x in s] while i >= 0: invalid = [] if i - 1 >= 0: invalid.append(ords[i - 1]) if i - 2 >= 0: invalid.append(ords[i - 2]) poss_j = [j for j in range(ords[i] + 1, k) if j not in invalid] if len(poss_j) == 0: i -= 1 else: j = min(poss_j) ords[i] = j for q in range(i + 1, n): invalid = [] if q- 1 >= 0: invalid.append(ords[q - 1]) if q- 2 >= 0: invalid.append(ords[q- 2]) j = 0 while j in invalid: j += 1 ords[q] = j chrs = [chr(x + ord("a")) for x in ords] ans = "".join(chrs) return ans return ""