sol_id
stringlengths
6
6
problem_id
stringlengths
6
6
problem_text
stringlengths
322
4.55k
solution_text
stringlengths
137
5.74k
8de221
f85331
You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a triple booking. A triple booking happens when three events have some non-empty intersection (i.e., some moment is common to all the three events.). The event can be represented as a pair of integers start and end that represents a booking on the half-open interval [start, end), the range of real numbers x such that start <= x < end. Implement the MyCalendarTwo class: MyCalendarTwo() Initializes the calendar object. boolean book(int start, int end) Returns true if the event can be added to the calendar successfully without causing a triple booking. Otherwise, return false and do not add the event to the calendar.   Example 1: Input ["MyCalendarTwo", "book", "book", "book", "book", "book", "book"] [[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]] Output [null, true, true, true, false, true, true] Explanation MyCalendarTwo myCalendarTwo = new MyCalendarTwo(); myCalendarTwo.book(10, 20); // return True, The event can be booked. myCalendarTwo.book(50, 60); // return True, The event can be booked. myCalendarTwo.book(10, 40); // return True, The event can be double booked. myCalendarTwo.book(5, 15); // return False, The event cannot be booked, because it would result in a triple booking. myCalendarTwo.book(5, 10); // return True, The event can be booked, as it does not use time 10 which is already double booked. myCalendarTwo.book(25, 55); // return True, The event can be booked, as the time in [25, 40) will be double booked with the third event, the time [40, 50) will be single booked, and the time [50, 55) will be double booked with the second event.   Constraints: 0 <= start < end <= 10^9 At most 1000 calls will be made to book.
class MyCalendarTwo(object): def __init__(self): self.cal = [] self.dep = [] def book(self, start, end): """ :type start: int :type end: int :rtype: bool """ dep = set(i for i, (a, b) in enumerate(self.cal) if (a <= start < b or start <= a < end)) if any(len(self.dep[j] & dep) > 0 for j in dep): return False self.cal.append((start,end)) self.dep.append(dep) return True
d0c14e
f85331
You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a triple booking. A triple booking happens when three events have some non-empty intersection (i.e., some moment is common to all the three events.). The event can be represented as a pair of integers start and end that represents a booking on the half-open interval [start, end), the range of real numbers x such that start <= x < end. Implement the MyCalendarTwo class: MyCalendarTwo() Initializes the calendar object. boolean book(int start, int end) Returns true if the event can be added to the calendar successfully without causing a triple booking. Otherwise, return false and do not add the event to the calendar.   Example 1: Input ["MyCalendarTwo", "book", "book", "book", "book", "book", "book"] [[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]] Output [null, true, true, true, false, true, true] Explanation MyCalendarTwo myCalendarTwo = new MyCalendarTwo(); myCalendarTwo.book(10, 20); // return True, The event can be booked. myCalendarTwo.book(50, 60); // return True, The event can be booked. myCalendarTwo.book(10, 40); // return True, The event can be double booked. myCalendarTwo.book(5, 15); // return False, The event cannot be booked, because it would result in a triple booking. myCalendarTwo.book(5, 10); // return True, The event can be booked, as it does not use time 10 which is already double booked. myCalendarTwo.book(25, 55); // return True, The event can be booked, as the time in [25, 40) will be double booked with the third event, the time [40, 50) will be single booked, and the time [50, 55) will be double booked with the second event.   Constraints: 0 <= start < end <= 10^9 At most 1000 calls will be made to book.
import sys from bisect import bisect_left class MyCalendarTwo: def __init__(self): self.intervals = [] self.counts = [0] self.endpoints = [-sys.maxsize, sys.maxsize] def new_endpoint(self, e): idx = bisect_left(self.endpoints, e) if self.endpoints[idx] != e: self.endpoints.insert(idx, e) self.counts.insert(idx, self.counts[idx-1]) def book(self, start, end): """ :type start: int :type end: int :rtype: bool """ if start >= end: return True # Add new endpoints self.new_endpoint(start) self.new_endpoint(end) # Check for new interval start_idx = bisect_left(self.endpoints, start) assert self.endpoints[start_idx] == start end_idx = bisect_left(self.endpoints, end) assert self.endpoints[end_idx] == end for idx in range(start_idx, end_idx): if self.counts[idx] >= 2: return False # Accept new interval for idx in range(start_idx, end_idx): self.counts[idx] += 1 self.intervals.append((start, end)) return True # Your MyCalendarTwo object will be instantiated and called as such: # obj = MyCalendarTwo() # param_1 = obj.book(start,end)
8caace
dce082
There are n cities numbered from 0 to n-1. Given the array edges where edges[i] = [fromi, toi, weighti] represents a bidirectional and weighted edge between cities fromi and toi, and given the integer distanceThreshold. Return the city with the smallest number of cities that are reachable through some path and whose distance is at most distanceThreshold, If there are multiple such cities, return the city with the greatest number. Notice that the distance of a path connecting cities i and j is equal to the sum of the edges' weights along that path.   Example 1: Input: n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4 Output: 3 Explanation: The figure above describes the graph.  The neighboring cities at a distanceThreshold = 4 for each city are: City 0 -> [City 1, City 2]  City 1 -> [City 0, City 2, City 3]  City 2 -> [City 0, City 1, City 3]  City 3 -> [City 1, City 2]  Cities 0 and 3 have 2 neighboring cities at a distanceThreshold = 4, but we have to return city 3 since it has the greatest number. Example 2: Input: n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 2 Output: 0 Explanation: The figure above describes the graph.  The neighboring cities at a distanceThreshold = 2 for each city are: City 0 -> [City 1]  City 1 -> [City 0, City 4]  City 2 -> [City 3, City 4]  City 3 -> [City 2, City 4] City 4 -> [City 1, City 2, City 3]  The city 0 has 1 neighboring city at a distanceThreshold = 2.   Constraints: 2 <= n <= 100 1 <= edges.length <= n * (n - 1) / 2 edges[i].length == 3 0 <= fromi < toi < n 1 <= weighti, distanceThreshold <= 10^4 All pairs (fromi, toi) are distinct.
class Solution(object): def findTheCity(self, n, edges, dT): """ :type n: int :type edges: List[List[int]] :type distanceThreshold: int :rtype: int There are n cities numbered from 0 to n-1. Given the array edges where edges[i] = [fromi, toi, weighti] represents a bidirectional and weighted edge between cities fromi and toi, and given the integer distanceThreshold. Return the city with the smallest number of cities that are reachable through some path and whose distance is at most distanceThreshold, If there are multiple such cities, return the city with the greatest number. Notice that the distance of a path connecting cities i and j is equal to the sum of the edges' weights along that path. """ """ graph = [{} for _ in range(n)] for u, v, w in edges: graph[u][v] = graph[v][u] = w ans = 0 ansreached = 0 for start in range(n): pq = [(0, start)] dist = {start: 0} while pq: d, node = heapq.heappop(pq) for nei, w in graph[node].iteritems(): d2 = d+w if d2 < dist.get(node, ) """ INF = float('inf') dist = [[INF] * n for _ in xrange(n)] for u, v, w in edges: dist[u][v] = dist[v][u] = w for u in xrange(n): dist[u][u] = 0 for k in xrange(n): for i in xrange(n): for j in xrange(n): cand = dist[i][k] + dist[k][j] if dist[i][j] > cand: dist[i][j] = cand ansreached = float('inf') for u in xrange(n): reached = 0 for v in xrange(n): if dist[u][v] <= dT: reached += 1 #print u, reached if reached <= ansreached: ansreached = reached ans = u return ans
15f1dc
dce082
There are n cities numbered from 0 to n-1. Given the array edges where edges[i] = [fromi, toi, weighti] represents a bidirectional and weighted edge between cities fromi and toi, and given the integer distanceThreshold. Return the city with the smallest number of cities that are reachable through some path and whose distance is at most distanceThreshold, If there are multiple such cities, return the city with the greatest number. Notice that the distance of a path connecting cities i and j is equal to the sum of the edges' weights along that path.   Example 1: Input: n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4 Output: 3 Explanation: The figure above describes the graph.  The neighboring cities at a distanceThreshold = 4 for each city are: City 0 -> [City 1, City 2]  City 1 -> [City 0, City 2, City 3]  City 2 -> [City 0, City 1, City 3]  City 3 -> [City 1, City 2]  Cities 0 and 3 have 2 neighboring cities at a distanceThreshold = 4, but we have to return city 3 since it has the greatest number. Example 2: Input: n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 2 Output: 0 Explanation: The figure above describes the graph.  The neighboring cities at a distanceThreshold = 2 for each city are: City 0 -> [City 1]  City 1 -> [City 0, City 4]  City 2 -> [City 3, City 4]  City 3 -> [City 2, City 4] City 4 -> [City 1, City 2, City 3]  The city 0 has 1 neighboring city at a distanceThreshold = 2.   Constraints: 2 <= n <= 100 1 <= edges.length <= n * (n - 1) / 2 edges[i].length == 3 0 <= fromi < toi < n 1 <= weighti, distanceThreshold <= 10^4 All pairs (fromi, toi) are distinct.
class Solution: def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int: inf = 1 << 60 g = [[inf] * n for _ in range(n)] for i in range(n): g[i][i] = 0 for u, v, w in edges: g[u][v] = w g[v][u] = w for k in range(n): for i in range(n): for j in range(n): g[i][j] = min(g[i][j], g[i][k] + g[k][j]) best = inf besti = -1 for x in range(n): cost = 0 for y in range(n): if g[x][y] <= distanceThreshold: cost += 1 #print(x, cost) if cost <= best: best = cost besti = x return besti
865685
355f21
You are given a 0-indexed array of strings garbage where garbage[i] represents the assortment of garbage at the ith house. garbage[i] consists only of the characters 'M', 'P' and 'G' representing one unit of metal, paper and glass garbage respectively. Picking up one unit of any type of garbage takes 1 minute. You are also given a 0-indexed integer array travel where travel[i] is the number of minutes needed to go from house i to house i + 1. There are three garbage trucks in the city, each responsible for picking up one type of garbage. Each garbage truck starts at house 0 and must visit each house in order; however, they do not need to visit every house. Only one garbage truck may be used at any given moment. While one truck is driving or picking up garbage, the other two trucks cannot do anything. Return the minimum number of minutes needed to pick up all the garbage.   Example 1: Input: garbage = ["G","P","GP","GG"], travel = [2,4,3] Output: 21 Explanation: The paper garbage truck: 1. Travels from house 0 to house 1 2. Collects the paper garbage at house 1 3. Travels from house 1 to house 2 4. Collects the paper garbage at house 2 Altogether, it takes 8 minutes to pick up all the paper garbage. The glass garbage truck: 1. Collects the glass garbage at house 0 2. Travels from house 0 to house 1 3. Travels from house 1 to house 2 4. Collects the glass garbage at house 2 5. Travels from house 2 to house 3 6. Collects the glass garbage at house 3 Altogether, it takes 13 minutes to pick up all the glass garbage. Since there is no metal garbage, we do not need to consider the metal garbage truck. Therefore, it takes a total of 8 + 13 = 21 minutes to collect all the garbage. Example 2: Input: garbage = ["MMM","PGM","GP"], travel = [3,10] Output: 37 Explanation: The metal garbage truck takes 7 minutes to pick up all the metal garbage. The paper garbage truck takes 15 minutes to pick up all the paper garbage. The glass garbage truck takes 15 minutes to pick up all the glass garbage. It takes a total of 7 + 15 + 15 = 37 minutes to collect all the garbage.   Constraints: 2 <= garbage.length <= 100000 garbage[i] consists of only the letters 'M', 'P', and 'G'. 1 <= garbage[i].length <= 10 travel.length == garbage.length - 1 1 <= travel[i] <= 100
class Solution: def garbageCollection(self, garbage: List[str], travel: List[int]) -> int: pref = [0] * (len(travel) + 1) for i, ti in enumerate(travel): pref[i + 1] = pref[i] + ti ans = sum(map(len, garbage)) for c in "GMP": idx = 0 for i, gi in enumerate(garbage): idx = i if c in gi else idx ans += pref[idx] return ans
0ceebc
355f21
You are given a 0-indexed array of strings garbage where garbage[i] represents the assortment of garbage at the ith house. garbage[i] consists only of the characters 'M', 'P' and 'G' representing one unit of metal, paper and glass garbage respectively. Picking up one unit of any type of garbage takes 1 minute. You are also given a 0-indexed integer array travel where travel[i] is the number of minutes needed to go from house i to house i + 1. There are three garbage trucks in the city, each responsible for picking up one type of garbage. Each garbage truck starts at house 0 and must visit each house in order; however, they do not need to visit every house. Only one garbage truck may be used at any given moment. While one truck is driving or picking up garbage, the other two trucks cannot do anything. Return the minimum number of minutes needed to pick up all the garbage.   Example 1: Input: garbage = ["G","P","GP","GG"], travel = [2,4,3] Output: 21 Explanation: The paper garbage truck: 1. Travels from house 0 to house 1 2. Collects the paper garbage at house 1 3. Travels from house 1 to house 2 4. Collects the paper garbage at house 2 Altogether, it takes 8 minutes to pick up all the paper garbage. The glass garbage truck: 1. Collects the glass garbage at house 0 2. Travels from house 0 to house 1 3. Travels from house 1 to house 2 4. Collects the glass garbage at house 2 5. Travels from house 2 to house 3 6. Collects the glass garbage at house 3 Altogether, it takes 13 minutes to pick up all the glass garbage. Since there is no metal garbage, we do not need to consider the metal garbage truck. Therefore, it takes a total of 8 + 13 = 21 minutes to collect all the garbage. Example 2: Input: garbage = ["MMM","PGM","GP"], travel = [3,10] Output: 37 Explanation: The metal garbage truck takes 7 minutes to pick up all the metal garbage. The paper garbage truck takes 15 minutes to pick up all the paper garbage. The glass garbage truck takes 15 minutes to pick up all the glass garbage. It takes a total of 7 + 15 + 15 = 37 minutes to collect all the garbage.   Constraints: 2 <= garbage.length <= 100000 garbage[i] consists of only the letters 'M', 'P', and 'G'. 1 <= garbage[i].length <= 10 travel.length == garbage.length - 1 1 <= travel[i] <= 100
class Solution(object): def garbageCollection(self, garbage, travel): """ :type garbage: List[str] :type travel: List[int] :rtype: int """ t, g, m, p, h, i, q = [0] * len(garbage), 0, 0, 0, 0, 0, 0 for j in range(1, len(garbage)): t[j] = t[j - 1] + travel[j - 1] for j in range(len(garbage)): for c in garbage[j]: g, h, m, i, p, q = t[j] if c == 'G' else g, h + 1 if c == 'G' else h, t[j] if c == 'M' else m, i + 1 if c == 'M' else i, t[j] if c == 'P' else p, q + 1 if c == 'P' else q return g + m + p + h + q + i
ceb40e
133e7b
You are given two string arrays words1 and words2. A string b is a subset of string a if every letter in b occurs in a including multiplicity. For example, "wrr" is a subset of "warrior" but is not a subset of "world". A string a from words1 is universal if for every string b in words2, b is a subset of a. Return an array of all the universal strings in words1. You may return the answer in any order.   Example 1: Input: words1 = ["amazon","apple","facebook","google","leetcode"], words2 = ["e","o"] Output: ["facebook","google","leetcode"] Example 2: Input: words1 = ["amazon","apple","facebook","google","leetcode"], words2 = ["l","e"] Output: ["apple","google","leetcode"]   Constraints: 1 <= words1.length, words2.length <= 10000 1 <= words1[i].length, words2[i].length <= 10 words1[i] and words2[i] consist only of lowercase English letters. All the strings of words1 are unique.
class Solution: def wordSubsets(self, A, B): """ :type A: List[str] :type B: List[str] :rtype: List[str] """ from collections import Counter needed = {} for bw in B: bwc = Counter(bw) for k in bwc: needed[k] = max(bwc[k], needed.get(k, 0)) res = [] for aw in A: awc = Counter(aw) isgood = True for k in needed: if k not in awc or awc[k] < needed[k]: isgood=False break if isgood: res.append(aw) return res
0f8e60
133e7b
You are given two string arrays words1 and words2. A string b is a subset of string a if every letter in b occurs in a including multiplicity. For example, "wrr" is a subset of "warrior" but is not a subset of "world". A string a from words1 is universal if for every string b in words2, b is a subset of a. Return an array of all the universal strings in words1. You may return the answer in any order.   Example 1: Input: words1 = ["amazon","apple","facebook","google","leetcode"], words2 = ["e","o"] Output: ["facebook","google","leetcode"] Example 2: Input: words1 = ["amazon","apple","facebook","google","leetcode"], words2 = ["l","e"] Output: ["apple","google","leetcode"]   Constraints: 1 <= words1.length, words2.length <= 10000 1 <= words1[i].length, words2[i].length <= 10 words1[i] and words2[i] consist only of lowercase English letters. All the strings of words1 are unique.
from collections import Counter class Solution(object): def wordSubsets(self, A, B): """ :type A: List[str] :type B: List[str] :rtype: List[str] """ res = [] cover = collections.defaultdict(int) for b in B: tmp = Counter(b) for k, v in tmp.items(): cover[k] = max(cover[k], v) for a in A: tmp = Counter(a) isValid = True for k, v in cover.items(): if tmp[k] < v: isValid = False break if isValid: res.append(a) return res
d15c4c
997f89
A split of an integer array is good if: The array is split into three non-empty contiguous subarrays - named left, mid, right respectively from left to right. The sum of the elements in left is less than or equal to the sum of the elements in mid, and the sum of the elements in mid is less than or equal to the sum of the elements in right. Given nums, an array of non-negative integers, return the number of good ways to split nums. As the number may be too large, return it modulo 10^9 + 7.   Example 1: Input: nums = [1,1,1] Output: 1 Explanation: The only good way to split nums is [1] [1] [1]. Example 2: Input: nums = [1,2,2,2,5,0] Output: 3 Explanation: There are three good ways of splitting nums: [1] [2] [2,2,5,0] [1] [2,2] [2,5,0] [1,2] [2,2] [5,0] Example 3: Input: nums = [3,2,1] Output: 0 Explanation: There is no good way to split nums.   Constraints: 3 <= nums.length <= 100000 0 <= nums[i] <= 10000
class Solution(object): def waysToSplit(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) s = [0] * (n+1) for i in xrange(n): s[i+1] = s[i] + nums[i] # 0 < i < j < n and s[i] <= s[j]-s[i] <= s[n]-s[j] # 2s[i] <= s[j] <= (s[n] + s[i]) // 2 j_min = j_max = r = 0 for i in xrange(1, n-1): j_min = max(j_min, i+1) while j_min < n and s[j_min] - s[i] < s[i]: j_min += 1 j_max = max(j_max, j_min) while j_max < n and s[j_max] - s[i] <= s[n] - s[j_max]: j_max += 1 if j_min < j_max: r += j_max - j_min return r % (10**9 + 7)
11bea1
997f89
A split of an integer array is good if: The array is split into three non-empty contiguous subarrays - named left, mid, right respectively from left to right. The sum of the elements in left is less than or equal to the sum of the elements in mid, and the sum of the elements in mid is less than or equal to the sum of the elements in right. Given nums, an array of non-negative integers, return the number of good ways to split nums. As the number may be too large, return it modulo 10^9 + 7.   Example 1: Input: nums = [1,1,1] Output: 1 Explanation: The only good way to split nums is [1] [1] [1]. Example 2: Input: nums = [1,2,2,2,5,0] Output: 3 Explanation: There are three good ways of splitting nums: [1] [2] [2,2,5,0] [1] [2,2] [2,5,0] [1,2] [2,2] [5,0] Example 3: Input: nums = [3,2,1] Output: 0 Explanation: There is no good way to split nums.   Constraints: 3 <= nums.length <= 100000 0 <= nums[i] <= 10000
class Solution: def waysToSplit(self, nums: List[int]) -> int: pre = [0] for num in nums: pre.append(pre[-1] + num) res = 0 n = len(nums) for i in range(1, n-1): left = pre[i] idx1 = bisect.bisect_left(pre, left * 2) idx1 = max(idx1, i + 1) r = pre[-1] - left mi = r // 2 idx2 = bisect.bisect_right(pre, left + mi) idx2 = min(idx2, n) if idx2 >= idx1: res += idx2 - idx1 return res % (10 ** 9 + 7)
75770c
1c6b8f
An n x n grid is composed of 1 x 1 squares where each 1 x 1 square consists of a '/', '\', or blank space ' '. These characters divide the square into contiguous regions. Given the grid grid represented as a string array, return the number of regions. Note that backslash characters are escaped, so a '\' is represented as '\\'.   Example 1: Input: grid = [" /","/ "] Output: 2 Example 2: Input: grid = [" /"," "] Output: 1 Example 3: Input: grid = ["/\\","\\/"] Output: 5 Explanation: Recall that because \ characters are escaped, "\\/" refers to \/, and "/\\" refers to /\.   Constraints: n == grid.length == grid[i].length 1 <= n <= 30 grid[i][j] is either '/', '\', or ' '.
import collections class Union: def __init__(self, n): self.parent = [i for i in range(n)] def search(self, i): if self.parent[i] != i: self.parent[i] = self.search(self.parent[i]) return self.parent[i] def merge(self, i, j): # print('merge', i, j) p = self.search(i) q = self.search(j) self.parent[p] = q class Solution: def regionsBySlashes(self, grid): """ :type grid: List[str] :rtype: int """ # for e in grid: # print('@' + e + '@') a = grid n = len(a) u = Union(n * n * 4) for i in range(n): for j in range(n): # print('loop', i, j) idx = i * n + j if a[i][j] == ' ': u.merge(idx * 4 + 0, idx * 4 + 1) u.merge(idx * 4 + 0, idx * 4 + 2) u.merge(idx * 4 + 0, idx * 4 + 3) elif a[i][j] == '/': u.merge(idx * 4 + 0, idx * 4 + 1) u.merge(idx * 4 + 2, idx * 4 + 3) else: u.merge(idx * 4 + 0, idx * 4 + 3) u.merge(idx * 4 + 1, idx * 4 + 2) if i != 0: u.merge(idx * 4 + 0, ((i - 1) * n + j) * 4 + 2) if j != 0: u.merge(idx * 4 + 1, (i * n + (j - 1)) * 4 + 3) if i != n - 1: u.merge(idx * 4 + 2, ((i + 1) * n + j) * 4 + 0) if j != n - 1: u.merge(idx * 4 + 3, (i * n + (j + 1)) * 4 + 1) # print([u.search(i) for i in range(n * n * 4)]) s = set([u.search(i) for i in range(n * n * 4)]) return len(s)
43f6e1
1c6b8f
An n x n grid is composed of 1 x 1 squares where each 1 x 1 square consists of a '/', '\', or blank space ' '. These characters divide the square into contiguous regions. Given the grid grid represented as a string array, return the number of regions. Note that backslash characters are escaped, so a '\' is represented as '\\'.   Example 1: Input: grid = [" /","/ "] Output: 2 Example 2: Input: grid = [" /"," "] Output: 1 Example 3: Input: grid = ["/\\","\\/"] Output: 5 Explanation: Recall that because \ characters are escaped, "\\/" refers to \/, and "/\\" refers to /\.   Constraints: n == grid.length == grid[i].length 1 <= n <= 30 grid[i][j] is either '/', '\', or ' '.
class Solution(object): def regionsBySlashes(self, grid): """ :type grid: List[str] :rtype: int """ from collections import deque self.M,self.N=len(grid),len(grid[0]) def flood(start): Q=deque() Q.append(start) while(Q): node=Q.popleft() if(node in Wall or node in See): continue if node[0]<=0 or node[0]>=self.M or node[1]<=0 or node[1]>=self.N: continue See.add(node) for dx,dy in [(0,0.25),(0,-0.25),(0.25,0),(-0.25,0)]: Q.append((node[0]+dx,node[1]+dy)) #print(node) Wall=set() for row in range(0,len(grid)): for col in range(0,len(grid[0])): if grid[row][col]=='\\': Wall.add((row, col)) Wall.add((row+0.25,col+0.25)) Wall.add((row+0.5, col+0.5)) Wall.add((row+0.75,col+0.75)) Wall.add((row+1, col+1)) elif grid[row][col]=='/': Wall.add((row, col+1)) Wall.add((row+0.25,col+0.75)) Wall.add((row+0.5, col+0.5)) Wall.add((row+0.75,col+0.25)) Wall.add((row+1, col)) See=set() Part=0 for row in range(0,len(grid)): for col in range(0,len(grid[0])): for dx in [0.25,0.5,0.75]: for dy in [0.25,0.5,0.75]: start=(row+dx,col+dy) if (start in See) or (start in Wall): continue else: #print(start) #print(See) Part+=1 #print("Part:",Part) flood(start) #print(Wall) return Part
2a8601
27dee7
A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. Design an algorithm to insert a new node to a complete binary tree keeping it complete after the insertion. Implement the CBTInserter class: CBTInserter(TreeNode root) Initializes the data structure with the root of the complete binary tree. int insert(int v) Inserts a TreeNode into the tree with value Node.val == val so that the tree remains complete, and returns the value of the parent of the inserted TreeNode. TreeNode get_root() Returns the root node of the tree.   Example 1: Input ["CBTInserter", "insert", "insert", "get_root"] [[[1, 2]], [3], [4], []] Output [null, 1, 2, [1, 2, 3, 4]] Explanation CBTInserter cBTInserter = new CBTInserter([1, 2]); cBTInserter.insert(3); // return 1 cBTInserter.insert(4); // return 2 cBTInserter.get_root(); // return [1, 2, 3, 4]   Constraints: The number of nodes in the tree will be in the range [1, 1000]. 0 <= Node.val <= 5000 root is a complete binary tree. 0 <= val <= 5000 At most 10000 calls will be made to insert and get_root.
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class CBTInserter(object): def __init__(self, root): """ :type root: TreeNode """ self.nodes = [] q = [root] while q: self.nodes.extend(q) q = [c for n in q for c in n.left, n.right if c] def insert(self, v): """ :type v: int :rtype: int """ i = len(self.nodes) self.nodes.append(TreeNode(v)) j = (i-1) // 2 if i % 2: self.nodes[j].left = self.nodes[i] else: self.nodes[j].right = self.nodes[i] return self.nodes[j].val def get_root(self): """ :rtype: TreeNode """ return self.nodes[0] # Your CBTInserter object will be instantiated and called as such: # obj = CBTInserter(root) # param_1 = obj.insert(v) # param_2 = obj.get_root()
04dec9
27dee7
A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. Design an algorithm to insert a new node to a complete binary tree keeping it complete after the insertion. Implement the CBTInserter class: CBTInserter(TreeNode root) Initializes the data structure with the root of the complete binary tree. int insert(int v) Inserts a TreeNode into the tree with value Node.val == val so that the tree remains complete, and returns the value of the parent of the inserted TreeNode. TreeNode get_root() Returns the root node of the tree.   Example 1: Input ["CBTInserter", "insert", "insert", "get_root"] [[[1, 2]], [3], [4], []] Output [null, 1, 2, [1, 2, 3, 4]] Explanation CBTInserter cBTInserter = new CBTInserter([1, 2]); cBTInserter.insert(3); // return 1 cBTInserter.insert(4); // return 2 cBTInserter.get_root(); // return [1, 2, 3, 4]   Constraints: The number of nodes in the tree will be in the range [1, 1000]. 0 <= Node.val <= 5000 root is a complete binary tree. 0 <= val <= 5000 At most 10000 calls will be made to insert and get_root.
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None import collections class CBTInserter: def __init__(self, root): """ :type root: TreeNode """ self.root = root self.q = collections.deque() self.q.append(self.root) while True: cur = self.q[0] if cur.left is not None: self.q.append(cur.left) if cur.right is not None: self.q.append(cur.right) if cur.left is not None and cur.right is not None: self.q.popleft() else: break def insert(self, v): """ :type v: int :rtype: int """ cur = self.q[0] node = TreeNode(v) if cur.left is None: cur.left = node self.q.append(node) ret = cur.val else: cur.right = node self.q.append(node) ret = cur.val self.q.popleft() return ret def get_root(self): """ :rtype: TreeNode """ return self.root # Your CBTInserter object will be instantiated and called as such: # obj = CBTInserter(root) # param_1 = obj.insert(v) # param_2 = obj.get_root()
d0545b
f5ecdc
You are given two 0-indexed integer arrays servers and tasks of lengths n​​​​​​ and m​​​​​​ respectively. servers[i] is the weight of the i​​​​​​th​​​​ server, and tasks[j] is the time needed to process the j​​​​​​th​​​​ task in seconds. Tasks are assigned to the servers using a task queue. Initially, all servers are free, and the queue is empty. At second j, the jth task is inserted into the queue (starting with the 0th task being inserted at second 0). As long as there are free servers and the queue is not empty, the task in the front of the queue will be assigned to a free server with the smallest weight, and in case of a tie, it is assigned to a free server with the smallest index. If there are no free servers and the queue is not empty, we wait until a server becomes free and immediately assign the next task. If multiple servers become free at the same time, then multiple tasks from the queue will be assigned in order of insertion following the weight and index priorities above. A server that is assigned task j at second t will be free again at second t + tasks[j]. Build an array ans​​​​ of length m, where ans[j] is the index of the server the j​​​​​​th task will be assigned to. Return the array ans​​​​.   Example 1: Input: servers = [3,3,2], tasks = [1,2,3,2,1,2] Output: [2,2,0,2,1,2] Explanation: Events in chronological order go as follows: - At second 0, task 0 is added and processed using server 2 until second 1. - At second 1, server 2 becomes free. Task 1 is added and processed using server 2 until second 3. - At second 2, task 2 is added and processed using server 0 until second 5. - At second 3, server 2 becomes free. Task 3 is added and processed using server 2 until second 5. - At second 4, task 4 is added and processed using server 1 until second 5. - At second 5, all servers become free. Task 5 is added and processed using server 2 until second 7. Example 2: Input: servers = [5,1,4,3,2], tasks = [2,1,2,4,5,2,1] Output: [1,4,1,4,1,3,2] Explanation: Events in chronological order go as follows: - At second 0, task 0 is added and processed using server 1 until second 2. - At second 1, task 1 is added and processed using server 4 until second 2. - At second 2, servers 1 and 4 become free. Task 2 is added and processed using server 1 until second 4. - At second 3, task 3 is added and processed using server 4 until second 7. - At second 4, server 1 becomes free. Task 4 is added and processed using server 1 until second 9. - At second 5, task 5 is added and processed using server 3 until second 7. - At second 6, task 6 is added and processed using server 2 until second 7.   Constraints: servers.length == n tasks.length == m 1 <= n, m <= 2 * 100000 1 <= servers[i], tasks[j] <= 2 * 100000
class Solution: def assignTasks(self, servers: List[int], tasks: List[int]) -> List[int]: d = [] s = [(x, i) for i, x in enumerate(servers)] heapq.heapify(s) to_do = collections.deque() res = [] for t in range(len(tasks)): while d and d[0][0] <= t: _, w, server_idx = heapq.heappop(d) heapq.heappush(s, (w, server_idx)) to_do.append(tasks[t]) while s and to_do: w, server_idx = heapq.heappop(s) time = to_do.popleft() res.append(server_idx) heapq.heappush(d, (t+time, w, server_idx)) while to_do: t, w, server_idx = heapq.heappop(d) heapq.heappush(s, (w, server_idx)) while d and d[0][0] <= t: _, w, server_idx = heapq.heappop(d) heapq.heappush(s, (w, server_idx)) while s and to_do: w, server_idx = heapq.heappop(s) time = to_do.popleft() res.append(server_idx) heapq.heappush(d, (t+time, w, server_idx)) return res
167369
f5ecdc
You are given two 0-indexed integer arrays servers and tasks of lengths n​​​​​​ and m​​​​​​ respectively. servers[i] is the weight of the i​​​​​​th​​​​ server, and tasks[j] is the time needed to process the j​​​​​​th​​​​ task in seconds. Tasks are assigned to the servers using a task queue. Initially, all servers are free, and the queue is empty. At second j, the jth task is inserted into the queue (starting with the 0th task being inserted at second 0). As long as there are free servers and the queue is not empty, the task in the front of the queue will be assigned to a free server with the smallest weight, and in case of a tie, it is assigned to a free server with the smallest index. If there are no free servers and the queue is not empty, we wait until a server becomes free and immediately assign the next task. If multiple servers become free at the same time, then multiple tasks from the queue will be assigned in order of insertion following the weight and index priorities above. A server that is assigned task j at second t will be free again at second t + tasks[j]. Build an array ans​​​​ of length m, where ans[j] is the index of the server the j​​​​​​th task will be assigned to. Return the array ans​​​​.   Example 1: Input: servers = [3,3,2], tasks = [1,2,3,2,1,2] Output: [2,2,0,2,1,2] Explanation: Events in chronological order go as follows: - At second 0, task 0 is added and processed using server 2 until second 1. - At second 1, server 2 becomes free. Task 1 is added and processed using server 2 until second 3. - At second 2, task 2 is added and processed using server 0 until second 5. - At second 3, server 2 becomes free. Task 3 is added and processed using server 2 until second 5. - At second 4, task 4 is added and processed using server 1 until second 5. - At second 5, all servers become free. Task 5 is added and processed using server 2 until second 7. Example 2: Input: servers = [5,1,4,3,2], tasks = [2,1,2,4,5,2,1] Output: [1,4,1,4,1,3,2] Explanation: Events in chronological order go as follows: - At second 0, task 0 is added and processed using server 1 until second 2. - At second 1, task 1 is added and processed using server 4 until second 2. - At second 2, servers 1 and 4 become free. Task 2 is added and processed using server 1 until second 4. - At second 3, task 3 is added and processed using server 4 until second 7. - At second 4, server 1 becomes free. Task 4 is added and processed using server 1 until second 9. - At second 5, task 5 is added and processed using server 3 until second 7. - At second 6, task 6 is added and processed using server 2 until second 7.   Constraints: servers.length == n tasks.length == m 1 <= n, m <= 2 * 100000 1 <= servers[i], tasks[j] <= 2 * 100000
class Solution(object): def assignTasks(self, servers, tasks): """ :type servers: List[int] :type tasks: List[int] :rtype: List[int] """ s,b = [],[] for i in range(len(servers)): heapq.heappush(s, (servers[i], i, 0)) ans = [None] * len(tasks) for i in range(len(tasks)): cur = max(cur, b[0][0]) if len(s) == 0 else i while len(b) > 0 and b[0][0] == cur: t = heapq.heappop(b) heapq.heappush(s, (t[1], t[2], t[0])) t = heapq.heappop(s) heapq.heappush(b, (max(t[2], i)+tasks[i], t[0], t[1])) ans[i] = t[1] return ans
d85de6
594c6e
Given the root of a binary tree, each node in the tree has a distinct value. After deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees). Return the roots of the trees in the remaining forest. You may return the result in any order.   Example 1: Input: root = [1,2,3,4,5,6,7], to_delete = [3,5] Output: [[1,2,null,4],[6],[7]] Example 2: Input: root = [1,2,4,null,3], to_delete = [3] Output: [[1,2,4]]   Constraints: The number of nodes in the given tree is at most 1000. Each node has a distinct value between 1 and 1000. to_delete.length <= 1000 to_delete contains distinct values between 1 and 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 dfs(self, root: TreeNode, detached: bool): if not root: return if detached and root.val not in self.x: self.ans.append(root) detached = (root.val in self.x) self.dfs(root.left, detached) self.dfs(root.right, detached) if root.left and root.left.val in self.x: root.left = None if root.right and root.right.val in self.x: root.right = None if root.val in self.x: del root def delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]: self.x = set(to_delete) self.ans = [] self.dfs(root, detached=True) return self.ans
a7a4f4
594c6e
Given the root of a binary tree, each node in the tree has a distinct value. After deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees). Return the roots of the trees in the remaining forest. You may return the result in any order.   Example 1: Input: root = [1,2,3,4,5,6,7], to_delete = [3,5] Output: [[1,2,null,4],[6],[7]] Example 2: Input: root = [1,2,4,null,3], to_delete = [3] Output: [[1,2,4]]   Constraints: The number of nodes in the given tree is at most 1000. Each node has a distinct value between 1 and 1000. to_delete.length <= 1000 to_delete contains distinct values between 1 and 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 delNodes(self, root, to_delete): """ :type root: TreeNode :type to_delete: List[int] :rtype: List[TreeNode] """ r = [] to_delete = set(to_delete) def dfs(node, parent=None): if not node: return if node.val in to_delete: if parent: if node is parent.left: parent.left = None if node is parent.right: parent.right = None dfs(node.left) dfs(node.right) else: if not parent: r.append(node) dfs(node.left, node) dfs(node.right, node) dfs(root) return r
101727
7cc347
You are given a 0-indexed m x n binary matrix matrix and an integer numSelect, which denotes the number of distinct columns you must select from matrix. Let us consider s = {c1, c2, ...., cnumSelect} as the set of columns selected by you. A row row is covered by s if: For each cell matrix[row][col] (0 <= col <= n - 1) where matrix[row][col] == 1, col is present in s or, No cell in row has a value of 1. You need to choose numSelect columns such that the number of rows that are covered is maximized. Return the maximum number of rows that can be covered by a set of numSelect columns.   Example 1: Input: matrix = [[0,0,0],[1,0,1],[0,1,1],[0,0,1]], numSelect = 2 Output: 3 Explanation: One possible way to cover 3 rows is shown in the diagram above. We choose s = {0, 2}. - Row 0 is covered because it has no occurrences of 1. - Row 1 is covered because the columns with value 1, i.e. 0 and 2 are present in s. - Row 2 is not covered because matrix[2][1] == 1 but 1 is not present in s. - Row 3 is covered because matrix[2][2] == 1 and 2 is present in s. Thus, we can cover three rows. Note that s = {1, 2} will also cover 3 rows, but it can be shown that no more than three rows can be covered. Example 2: Input: matrix = [[1],[0]], numSelect = 1 Output: 2 Explanation: Selecting the only column will result in both rows being covered since the entire matrix is selected. Therefore, we return 2.   Constraints: m == matrix.length n == matrix[i].length 1 <= m, n <= 12 matrix[i][j] is either 0 or 1. 1 <= numSelect <= n
class Solution: def maximumRows(self, mat: List[List[int]], cols: int) -> int: m, n = len(mat), len(mat[0]) ans = 0 for x in range(1<<n): if x.bit_count() > cols: continue t = 0 for i in range(m): if all(mat[i][j] == 0 or 1<<j & x for j in range(n)): t += 1 ans = max(ans, t) return ans
3d36ef
7cc347
You are given a 0-indexed m x n binary matrix matrix and an integer numSelect, which denotes the number of distinct columns you must select from matrix. Let us consider s = {c1, c2, ...., cnumSelect} as the set of columns selected by you. A row row is covered by s if: For each cell matrix[row][col] (0 <= col <= n - 1) where matrix[row][col] == 1, col is present in s or, No cell in row has a value of 1. You need to choose numSelect columns such that the number of rows that are covered is maximized. Return the maximum number of rows that can be covered by a set of numSelect columns.   Example 1: Input: matrix = [[0,0,0],[1,0,1],[0,1,1],[0,0,1]], numSelect = 2 Output: 3 Explanation: One possible way to cover 3 rows is shown in the diagram above. We choose s = {0, 2}. - Row 0 is covered because it has no occurrences of 1. - Row 1 is covered because the columns with value 1, i.e. 0 and 2 are present in s. - Row 2 is not covered because matrix[2][1] == 1 but 1 is not present in s. - Row 3 is covered because matrix[2][2] == 1 and 2 is present in s. Thus, we can cover three rows. Note that s = {1, 2} will also cover 3 rows, but it can be shown that no more than three rows can be covered. Example 2: Input: matrix = [[1],[0]], numSelect = 1 Output: 2 Explanation: Selecting the only column will result in both rows being covered since the entire matrix is selected. Therefore, we return 2.   Constraints: m == matrix.length n == matrix[i].length 1 <= m, n <= 12 matrix[i][j] is either 0 or 1. 1 <= numSelect <= n
class Solution(object): def maximumRows(self, mat, cols): """ :type mat: List[List[int]] :type cols: int :rtype: int """ m, n = len(mat), len(mat[0]) mm = 1<<n r = 0 for x in range(mm): c=0 for i in range(n): if x&(1<<i): c+=1 if c!=cols: continue cc=0 for i in range(m): fit=1 for j in range(n): if mat[i][j]==1 and ((1<<j)&x)==0: fit=0 break cc+=fit r= max(r, cc) return r
d20c77
b7a000
There is a one-dimensional garden on the x-axis. The garden starts at the point 0 and ends at the point n. (i.e The length of the garden is n). There are n + 1 taps located at points [0, 1, ..., n] in the garden. Given an integer n and an integer array ranges of length n + 1 where ranges[i] (0-indexed) means the i-th tap can water the area [i - ranges[i], i + ranges[i]] if it was open. Return the minimum number of taps that should be open to water the whole garden, If the garden cannot be watered return -1.   Example 1: Input: n = 5, ranges = [3,4,1,1,0,0] Output: 1 Explanation: The tap at point 0 can cover the interval [-3,3] The tap at point 1 can cover the interval [-3,5] The tap at point 2 can cover the interval [1,3] The tap at point 3 can cover the interval [2,4] The tap at point 4 can cover the interval [4,4] The tap at point 5 can cover the interval [5,5] Opening Only the second tap will water the whole garden [0,5] Example 2: Input: n = 3, ranges = [0,0,0,0] Output: -1 Explanation: Even if you activate all the four taps you cannot water the whole garden.   Constraints: 1 <= n <= 10000 ranges.length == n + 1 0 <= ranges[i] <= 100
class Solution(object): def minTaps(self, n, ranges): """ :type n: int :type ranges: List[int] :rtype: int """ t = [0] * (n+1) for i, v in enumerate(ranges): x, y = max(0, i-v), min(n, i+v) t[x] = max(t[x], y) r = 0 i = j = k = r = 0 while j < n: while i <= j: k = max(k, t[i]) i += 1 if k <= j: return -1 j = k r += 1 return r
10bb3e
b7a000
There is a one-dimensional garden on the x-axis. The garden starts at the point 0 and ends at the point n. (i.e The length of the garden is n). There are n + 1 taps located at points [0, 1, ..., n] in the garden. Given an integer n and an integer array ranges of length n + 1 where ranges[i] (0-indexed) means the i-th tap can water the area [i - ranges[i], i + ranges[i]] if it was open. Return the minimum number of taps that should be open to water the whole garden, If the garden cannot be watered return -1.   Example 1: Input: n = 5, ranges = [3,4,1,1,0,0] Output: 1 Explanation: The tap at point 0 can cover the interval [-3,3] The tap at point 1 can cover the interval [-3,5] The tap at point 2 can cover the interval [1,3] The tap at point 3 can cover the interval [2,4] The tap at point 4 can cover the interval [4,4] The tap at point 5 can cover the interval [5,5] Opening Only the second tap will water the whole garden [0,5] Example 2: Input: n = 3, ranges = [0,0,0,0] Output: -1 Explanation: Even if you activate all the four taps you cannot water the whole garden.   Constraints: 1 <= n <= 10000 ranges.length == n + 1 0 <= ranges[i] <= 100
from collections import deque class Solution: def minTaps(self, n: int, ranges: List[int]) -> int: bs = [(i - r, i) for i, r in enumerate(ranges)] bs.sort() bs = deque(bs) x = 0 ret = 0 while x < n and bs: nx = x while bs and bs[0][0] <= x: nx = max(nx, ranges[bs[0][1]] + bs[0][1]) bs.popleft() if x == nx: break x = nx ret += 1 if x < n: ret = -1 return ret
2f9d41
75f39e
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 500 grid consists only of lowercase English letters.
class Solution(object): def containsCycle(self, A): R, C = len(A), len(A[0]) def dfs(r, c, v, pr, pc): color[r, c] = GRAY for nr, nc in ((r-1, c), (r, c-1), (r+1, c), (r, c+1)): if 0 <= nr <R and 0<=nc<C and A[nr][nc] == v and (pr!=nr or pc!=nc): nei = nr,nc co = color[nr,nc] if co == WHITE: if not dfs(nr,nc,v, r,c): return False elif co == GRAY: return False color[r,c] = BLACK return True WHITE,GRAY,BLACK = 0,1,2 color = collections.defaultdict(int) for r, row in enumerate(A): for c, v in enumerate(row): if color[r,c] == WHITE: if not dfs(r, c, v, -1,-1): return True return False
20b7ee
75f39e
Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid. A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell. Return true if any cycle of the same value exists in grid, otherwise, return false.   Example 1: Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]] Output: true Explanation: There are two valid cycles shown in different colors in the image below: Example 2: Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]] Output: true Explanation: There is only one valid cycle highlighted in the image below: Example 3: Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]] Output: false   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 500 grid consists only of lowercase English letters.
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: rows = len(grid) cols = len(grid[0]) visited = [[False] * cols for _ in range(rows)] found = False def go(x, y, px, py): visited[x][y] = True nonlocal found for dx, dy in [(1, 0), (0, 1), (-1, 0), (0, -1)]: nx, ny = x + dx, y + dy if 0 <= nx < rows and 0 <= ny < cols and grid[nx][ny] == grid[x][y] and not (nx == px and ny == py): if visited[nx][ny]: found = True else: go(nx, ny, x, y) for x in range(rows): for y in range(cols): if not visited[x][y] and not found: go(x, y, -1, -1) return found
68dab7
956398
You have n robots. You are given two 0-indexed integer arrays, chargeTimes and runningCosts, both of length n. The ith robot costs chargeTimes[i] units to charge and costs runningCosts[i] units to run. You are also given an integer budget. The total cost of running k chosen robots is equal to max(chargeTimes) + k * sum(runningCosts), where max(chargeTimes) is the largest charge cost among the k robots and sum(runningCosts) is the sum of running costs among the k robots. Return the maximum number of consecutive robots you can run such that the total cost does not exceed budget.   Example 1: Input: chargeTimes = [3,6,1,3,4], runningCosts = [2,1,3,4,5], budget = 25 Output: 3 Explanation: It is possible to run all individual and consecutive pairs of robots within budget. To obtain answer 3, consider the first 3 robots. The total cost will be max(3,6,1) + 3 * sum(2,1,3) = 6 + 3 * 6 = 24 which is less than 25. It can be shown that it is not possible to run more than 3 consecutive robots within budget, so we return 3. Example 2: Input: chargeTimes = [11,12,19], runningCosts = [10,8,7], budget = 19 Output: 0 Explanation: No robot can be run that does not exceed the budget, so we return 0.   Constraints: chargeTimes.length == runningCosts.length == n 1 <= n <= 5 * 10000 1 <= chargeTimes[i], runningCosts[i] <= 100000 1 <= budget <= 10^15
class Solution: def maximumRobots(self, chargeTimes: List[int], runningCosts: List[int], budget: int) -> int: h = list(accumulate(runningCosts)) + [0] q = deque([]) n = len(chargeTimes) l = 0 t = 0 ans = 0 for i in range(n): while q and chargeTimes[q[-1]] <= chargeTimes[i]: q.pop() q.append(i) t = chargeTimes[q[0]] + (i-l+1) * (h[i] - h[l-1]) if t > budget: if q[0] == l: q.popleft() l += 1 continue ans = max(ans, i-l+1) return ans
5aab1a
956398
You have n robots. You are given two 0-indexed integer arrays, chargeTimes and runningCosts, both of length n. The ith robot costs chargeTimes[i] units to charge and costs runningCosts[i] units to run. You are also given an integer budget. The total cost of running k chosen robots is equal to max(chargeTimes) + k * sum(runningCosts), where max(chargeTimes) is the largest charge cost among the k robots and sum(runningCosts) is the sum of running costs among the k robots. Return the maximum number of consecutive robots you can run such that the total cost does not exceed budget.   Example 1: Input: chargeTimes = [3,6,1,3,4], runningCosts = [2,1,3,4,5], budget = 25 Output: 3 Explanation: It is possible to run all individual and consecutive pairs of robots within budget. To obtain answer 3, consider the first 3 robots. The total cost will be max(3,6,1) + 3 * sum(2,1,3) = 6 + 3 * 6 = 24 which is less than 25. It can be shown that it is not possible to run more than 3 consecutive robots within budget, so we return 3. Example 2: Input: chargeTimes = [11,12,19], runningCosts = [10,8,7], budget = 19 Output: 0 Explanation: No robot can be run that does not exceed the budget, so we return 0.   Constraints: chargeTimes.length == runningCosts.length == n 1 <= n <= 5 * 10000 1 <= chargeTimes[i], runningCosts[i] <= 100000 1 <= budget <= 10^15
class Solution(object): def maximumRobots(self, chargeTimes, runningCosts, budget): """ :type chargeTimes: List[int] :type runningCosts: List[int] :type budget: int :rtype: int """ h = [] n = len(chargeTimes) i=0 j=0 s = 0 rr = 0 while i<n: c, r = chargeTimes[i], runningCosts[i] s+=r heappush(h, (-c, i)) # print i, j while True: while h: hc, hi = h[0] if hi>=j: break heappop(h) if not h: break x = -h[0][0]+(i-j+1)*s if x<=budget: rr=max(i-j+1, rr) break s-=runningCosts[j] j+=1 i+=1 return rr
d45fea
0268b6
You have a list arr of all integers in the range [1, n] sorted in a strictly increasing order. Apply the following algorithm on arr: Starting from left to right, remove the first number and every other number afterward until you reach the end of the list. Repeat the previous step again, but this time from right to left, remove the rightmost number and every other number from the remaining numbers. Keep repeating the steps again, alternating left to right and right to left, until a single number remains. Given the integer n, return the last number that remains in arr.   Example 1: Input: n = 9 Output: 6 Explanation: arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] arr = [2, 4, 6, 8] arr = [2, 6] arr = [6] Example 2: Input: n = 1 Output: 1   Constraints: 1 <= n <= 10^9
class Solution(object): def lastRemaining(self, n): """ :type n: int :rtype: int """ return self.solve(1,1,n) def solve(self,start,span,n): if n==1: return start start+=span n/=2 span*=2 if n<=2: return start if n%2==1: start+=span n/=2 span*=2 return self.solve(start,span,n)
36fc63
34ed88
You are given a 2D integer array, queries. For each queries[i], where queries[i] = [ni, ki], find the number of different ways you can place positive integers into an array of size ni such that the product of the integers is ki. As the number of ways may be too large, the answer to the ith query is the number of ways modulo 10^9 + 7. Return an integer array answer where answer.length == queries.length, and answer[i] is the answer to the ith query.   Example 1: Input: queries = [[2,6],[5,1],[73,660]] Output: [4,1,50734910] Explanation: Each query is independent. [2,6]: There are 4 ways to fill an array of size 2 that multiply to 6: [1,6], [2,3], [3,2], [6,1]. [5,1]: There is 1 way to fill an array of size 5 that multiply to 1: [1,1,1,1,1]. [73,660]: There are 1050734917 ways to fill an array of size 73 that multiply to 660. 1050734917 modulo 10^9 + 7 = 50734910. Example 2: Input: queries = [[1,1],[2,2],[3,3],[4,4],[5,5]] Output: [1,2,3,10,5]   Constraints: 1 <= queries.length <= 10000 1 <= ni, ki <= 10000
class Solution(object): def waysToFillArray(self, queries): primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113] ress = [] mod = 10**9 + 7 def combi(a, b): res = 1 b = min(b, a - b) for i in xrange(b): res *= a - i res /= i + 1 return res % mod for n, k in queries: # print 'n,k', n, k res = 1 for p in primes: count = 0 if p > k: break while k % p == 0: count += 1 k /= p res *= combi(count + n - 1, count) # print count, n, res res %= mod if k > 1: res = res * n % mod ress.append(res) return ress
d0a238
34ed88
You are given a 2D integer array, queries. For each queries[i], where queries[i] = [ni, ki], find the number of different ways you can place positive integers into an array of size ni such that the product of the integers is ki. As the number of ways may be too large, the answer to the ith query is the number of ways modulo 10^9 + 7. Return an integer array answer where answer.length == queries.length, and answer[i] is the answer to the ith query.   Example 1: Input: queries = [[2,6],[5,1],[73,660]] Output: [4,1,50734910] Explanation: Each query is independent. [2,6]: There are 4 ways to fill an array of size 2 that multiply to 6: [1,6], [2,3], [3,2], [6,1]. [5,1]: There is 1 way to fill an array of size 5 that multiply to 1: [1,1,1,1,1]. [73,660]: There are 1050734917 ways to fill an array of size 73 that multiply to 660. 1050734917 modulo 10^9 + 7 = 50734910. Example 2: Input: queries = [[1,1],[2,2],[3,3],[4,4],[5,5]] Output: [1,2,3,10,5]   Constraints: 1 <= queries.length <= 10000 1 <= ni, ki <= 10000
class Solution: def waysToFillArray(self, que: List[List[int]]) -> List[int]: a=[] mod=int(10**9+7) def get(p,n): v=1 for i in range(p): v*=n+i v//=i+1 return v%mod for n,k in que: ans=1 for i in range(2,k+1): if i*i>k: break if k%i: continue c=0 while k%i==0: c+=1 k//=i ans=(ans*get(c,n))%mod if k>1: ans=(ans*get(1,n))%mod a.append(ans%mod) # a=[x%mod for x in a] return a
08e94c
7721d3
Given a string s and an integer k, return true if s is a k-palindrome. A string is k-palindrome if it can be transformed into a palindrome by removing at most k characters from it. Example 1: Input: s = "abcdeca", k = 2 Output: true Explanation: Remove 'b' and 'e' characters. Example 2: Input: s = "abbababa", k = 1 Output: true Constraints: 1 <= s.length <= 1000 s consists of only lowercase English letters. 1 <= k <= s.length
from functools import lru_cache class Solution: def isValidPalindrome(self, s: str, k: int) -> bool: n = len(s) t = s[::-1] @lru_cache(None) def dp(i, j): if i == 0 or j == 0: return i + j i-=1;j-=1 if s[i] == t[j]: return dp(i, j) return 1 + min(dp(i+1,j), dp(i,j+1)) return dp(n, n) <= 2 * k
f6a8ff
7721d3
Given a string s and an integer k, return true if s is a k-palindrome. A string is k-palindrome if it can be transformed into a palindrome by removing at most k characters from it. Example 1: Input: s = "abcdeca", k = 2 Output: true Explanation: Remove 'b' and 'e' characters. Example 2: Input: s = "abbababa", k = 1 Output: true Constraints: 1 <= s.length <= 1000 s consists of only lowercase English letters. 1 <= k <= s.length
class Solution(object): def isValidPalindrome(self, s, k): """ :type s: str :type k: int :rtype: bool """ n=len(s) a,b=s,s[::-1] ans=[[0]*(n+1) for i in range(n+1)] for i in range(n+1): for j in range(n+1): if i==0 or j==0: ans[i][j]=0 elif a[i-1]==b[j-1]: ans[i][j]=1+ans[i-1][j-1] else: ans[i][j]=max(ans[i-1][j],ans[i][j-1]) return ans[n][n]>=n-k
afe9a6
6f26b5
There is a room with n bulbs labeled from 1 to n that all are turned on initially, and four buttons on the wall. Each of the four buttons has a different functionality where: Button 1: Flips the status of all the bulbs. Button 2: Flips the status of all the bulbs with even labels (i.e., 2, 4, ...). Button 3: Flips the status of all the bulbs with odd labels (i.e., 1, 3, ...). Button 4: Flips the status of all the bulbs with a label j = 3k + 1 where k = 0, 1, 2, ... (i.e., 1, 4, 7, 10, ...). You must make exactly presses button presses in total. For each press, you may pick any of the four buttons to press. Given the two integers n and presses, return the number of different possible statuses after performing all presses button presses.   Example 1: Input: n = 1, presses = 1 Output: 2 Explanation: Status can be: - [off] by pressing button 1 - [on] by pressing button 2 Example 2: Input: n = 2, presses = 1 Output: 3 Explanation: Status can be: - [off, off] by pressing button 1 - [on, off] by pressing button 2 - [off, on] by pressing button 3 Example 3: Input: n = 3, presses = 1 Output: 4 Explanation: Status can be: - [off, off, off] by pressing button 1 - [off, on, off] by pressing button 2 - [on, off, on] by pressing button 3 - [off, on, on] by pressing button 4   Constraints: 1 <= n <= 1000 0 <= presses <= 1000
class Solution(object): def flipLights(self, n, m): """ :type n: int :type m: int :rtype: int """ def cnt(p): res = 0 while p: res += p % 2 p /= 2 return res g = set() for i in range(16): num = cnt(i) if num % 2 == m % 2 and num <= m: s = [' '] * n for j in range(1, n + 1): match = 0 if i & 1: match += 1 if (i & 2) and j % 2 == 0: match += 1 if (i & 4) and j % 2 == 1: match += 1 if (i & 8) and (j - 1) % 3 == 0: match += 1 if match % 2 == 0: s[j - 1] = '1' else: s[j - 1] = '0' s = ''.join(s) g.add(s) return len(g)
e6371f
6f26b5
There is a room with n bulbs labeled from 1 to n that all are turned on initially, and four buttons on the wall. Each of the four buttons has a different functionality where: Button 1: Flips the status of all the bulbs. Button 2: Flips the status of all the bulbs with even labels (i.e., 2, 4, ...). Button 3: Flips the status of all the bulbs with odd labels (i.e., 1, 3, ...). Button 4: Flips the status of all the bulbs with a label j = 3k + 1 where k = 0, 1, 2, ... (i.e., 1, 4, 7, 10, ...). You must make exactly presses button presses in total. For each press, you may pick any of the four buttons to press. Given the two integers n and presses, return the number of different possible statuses after performing all presses button presses.   Example 1: Input: n = 1, presses = 1 Output: 2 Explanation: Status can be: - [off] by pressing button 1 - [on] by pressing button 2 Example 2: Input: n = 2, presses = 1 Output: 3 Explanation: Status can be: - [off, off] by pressing button 1 - [on, off] by pressing button 2 - [off, on] by pressing button 3 Example 3: Input: n = 3, presses = 1 Output: 4 Explanation: Status can be: - [off, off, off] by pressing button 1 - [off, on, off] by pressing button 2 - [on, off, on] by pressing button 3 - [off, on, on] by pressing button 4   Constraints: 1 <= n <= 1000 0 <= presses <= 1000
class Solution: def flipLights(self, n, m): """ :type n: int :type m: int :rtype: int """ if n == 0: return 1 if n == 1: return 1 if m == 0 else 2 if n == 2: if m == 0: return 1 elif m == 1: return 3 else: return 4 if m == 0: return 1 elif m == 1: return 4 elif m == 2: return 7 else: return 8
84db93
61d9a8
You are given a positive integer 0-indexed array nums. A subset of the array nums is square-free if the product of its elements is a square-free integer. A square-free integer is an integer that is divisible by no square number other than 1. Return the number of square-free non-empty subsets of the array nums. Since the answer may be too large, return it modulo 10^9 + 7. A non-empty subset of nums is an array that can be obtained by deleting some (possibly none but not all) elements from nums. Two subsets are different if and only if the chosen indices to delete are different.   Example 1: Input: nums = [3,4,4,5] Output: 3 Explanation: There are 3 square-free subsets in this example: - The subset consisting of the 0th element [3]. The product of its elements is 3, which is a square-free integer. - The subset consisting of the 3rd element [5]. The product of its elements is 5, which is a square-free integer. - The subset consisting of 0th and 3rd elements [3,5]. The product of its elements is 15, which is a square-free integer. It can be proven that there are no more than 3 square-free subsets in the given array. Example 2: Input: nums = [1] Output: 1 Explanation: There is 1 square-free subset in this example: - The subset consisting of the 0th element [1]. The product of its elements is 1, which is a square-free integer. It can be proven that there is no more than 1 square-free subset in the given array.   Constraints: 1 <= nums.length <= 1000 1 <= nums[i] <= 30
class Solution(object): def squareFreeSubsets(self, nums): """ :type nums: List[int] :rtype: int """ def _factor(v): r = [] for p in xrange(2, v): if p*p > v: break c = 0 while v % p == 0: v //= p c += 1 if c: r.append((p, c)) if v > 1: r.append((v, 1)) return r a = [] m = 0 d = {} for v in nums: f = _factor(v) if any(e>=2 for _, e in f): continue x = 0 for p, _ in f: if p not in d: d[p] = m m += 1 x |= (1<<d[p]) a.append(x) f = [0] * (1<<m) f[0] = 1 mod = 10**9 + 7 for i in a: for j in xrange(1<<m): if (i & j) == 0: f[i^j] = (f[j] + f[i^j]) % mod return (sum(f) - 1) % mod
945be2
61d9a8
You are given a positive integer 0-indexed array nums. A subset of the array nums is square-free if the product of its elements is a square-free integer. A square-free integer is an integer that is divisible by no square number other than 1. Return the number of square-free non-empty subsets of the array nums. Since the answer may be too large, return it modulo 10^9 + 7. A non-empty subset of nums is an array that can be obtained by deleting some (possibly none but not all) elements from nums. Two subsets are different if and only if the chosen indices to delete are different.   Example 1: Input: nums = [3,4,4,5] Output: 3 Explanation: There are 3 square-free subsets in this example: - The subset consisting of the 0th element [3]. The product of its elements is 3, which is a square-free integer. - The subset consisting of the 3rd element [5]. The product of its elements is 5, which is a square-free integer. - The subset consisting of 0th and 3rd elements [3,5]. The product of its elements is 15, which is a square-free integer. It can be proven that there are no more than 3 square-free subsets in the given array. Example 2: Input: nums = [1] Output: 1 Explanation: There is 1 square-free subset in this example: - The subset consisting of the 0th element [1]. The product of its elements is 1, which is a square-free integer. It can be proven that there is no more than 1 square-free subset in the given array.   Constraints: 1 <= nums.length <= 1000 1 <= nums[i] <= 30
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] np = len(primes) msk = (1 << np) - 1 mod = int(1e9 + 7) def tobit(n: int) -> int: ans = 0 for i, prime in enumerate(primes): c = 0 while n % prime == 0: n //= prime c += 1 if c >= 2: return -1 elif c == 1: ans ^= 1 << i return ans class Solution: def squareFreeSubsets(self, nums: List[int]) -> int: cnt = [0] * (1 << np) cnt[0] = 1 bits = [0] + [tobit(i) for i in range(1, 31)] for num in nums: bit = bits[num] if bit == -1: continue s = msk ^ bit while s > 0: cnt[s ^ bit] = (cnt[s ^ bit] + cnt[s]) % mod s = (s - 1) & (msk ^ bit) cnt[bit] = (cnt[bit] + cnt[0]) % mod return (sum(cnt) + mod - 1) % mod
02e2c3
088d27
Given two integers n and k, return the kth lexicographically smallest integer in the range [1, n].   Example 1: Input: n = 13, k = 2 Output: 10 Explanation: The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10. Example 2: Input: n = 1, k = 1 Output: 1   Constraints: 1 <= k <= n <= 10^9
class Solution(object): def numCount(self, n, prefix): if prefix[0] == '0': return 0 t = 1 result = 0 old_prefix_len = len(prefix) ll = old_prefix_len while ll < len(n): result += t ll += 1 t *= 10 if int(prefix) < int(n[:old_prefix_len]): result += t elif int(prefix) == int(n[:old_prefix_len]): if n == prefix: result += 1 else: result += int(n[old_prefix_len:]) + 1 return result def findKthNumber(self, n, k): """ :type n: int :type k: int :rtype: int """ n = str(n) answer = "" while k > 0: for i in xrange(10): ct = self.numCount(n, answer + str(i)) if ct < k: k -= ct elif ct >= k: answer += str(i) k -= 1 break return int(answer)
3fb78a
43d5d5
You are given two arrays rowSum and colSum of non-negative integers where rowSum[i] is the sum of the elements in the ith row and colSum[j] is the sum of the elements of the jth column of a 2D matrix. In other words, you do not know the elements of the matrix, but you do know the sums of each row and column. Find any matrix of non-negative integers of size rowSum.length x colSum.length that satisfies the rowSum and colSum requirements. Return a 2D array representing any matrix that fulfills the requirements. It's guaranteed that at least one matrix that fulfills the requirements exists.   Example 1: Input: rowSum = [3,8], colSum = [4,7] Output: [[3,0], [1,7]] Explanation: 0th row: 3 + 0 = 3 == rowSum[0] 1st row: 1 + 7 = 8 == rowSum[1] 0th column: 3 + 1 = 4 == colSum[0] 1st column: 0 + 7 = 7 == colSum[1] The row and column sums match, and all matrix elements are non-negative. Another possible matrix is: [[1,2], [3,5]] Example 2: Input: rowSum = [5,7,10], colSum = [8,6,8] Output: [[0,5,0], [6,1,0], [2,0,8]]   Constraints: 1 <= rowSum.length, colSum.length <= 500 0 <= rowSum[i], colSum[i] <= 10^8 sum(rowSum) == sum(colSum)
class Solution: def restoreMatrix(self, rowSum: List[int], colSum: List[int]) -> List[List[int]]: R = len(rowSum) C = len(colSum) ret = [[0] * C for _ in range(R)] for i in range(R) : for j in range(C) : ret[i][j] = min(rowSum[i], colSum[j]) rowSum[i] -= ret[i][j] colSum[j] -= ret[i][j] return ret
9670a9
43d5d5
You are given two arrays rowSum and colSum of non-negative integers where rowSum[i] is the sum of the elements in the ith row and colSum[j] is the sum of the elements of the jth column of a 2D matrix. In other words, you do not know the elements of the matrix, but you do know the sums of each row and column. Find any matrix of non-negative integers of size rowSum.length x colSum.length that satisfies the rowSum and colSum requirements. Return a 2D array representing any matrix that fulfills the requirements. It's guaranteed that at least one matrix that fulfills the requirements exists.   Example 1: Input: rowSum = [3,8], colSum = [4,7] Output: [[3,0], [1,7]] Explanation: 0th row: 3 + 0 = 3 == rowSum[0] 1st row: 1 + 7 = 8 == rowSum[1] 0th column: 3 + 1 = 4 == colSum[0] 1st column: 0 + 7 = 7 == colSum[1] The row and column sums match, and all matrix elements are non-negative. Another possible matrix is: [[1,2], [3,5]] Example 2: Input: rowSum = [5,7,10], colSum = [8,6,8] Output: [[0,5,0], [6,1,0], [2,0,8]]   Constraints: 1 <= rowSum.length, colSum.length <= 500 0 <= rowSum[i], colSum[i] <= 10^8 sum(rowSum) == sum(colSum)
class Solution(object): def restoreMatrix(self, rowSum, colSum): """ :type rowSum: List[int] :type colSum: List[int] :rtype: List[List[int]] """ M, N = len(rowSum), len(colSum) res = [[0] * N for _ in xrange(M)] for i in xrange(M): rem = rowSum[i] for j in xrange(N): res[i][j] = min(rem, colSum[j]) rem -= res[i][j] colSum[j] -= res[i][j] return res
d1290a
5070cf
Given an integer array queries and a positive integer intLength, return an array answer where answer[i] is either the queries[i]th smallest positive palindrome of length intLength or -1 if no such palindrome exists. A palindrome is a number that reads the same backwards and forwards. Palindromes cannot have leading zeros.   Example 1: Input: queries = [1,2,3,4,5,90], intLength = 3 Output: [101,111,121,131,141,999] Explanation: The first few palindromes of length 3 are: 101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, ... The 90th palindrome of length 3 is 999. Example 2: Input: queries = [2,4,6], intLength = 4 Output: [1111,1331,1551] Explanation: The first six palindromes of length 4 are: 1001, 1111, 1221, 1331, 1441, and 1551.   Constraints: 1 <= queries.length <= 5 * 10000 1 <= queries[i] <= 10^9 1 <= intLength <= 15
class Solution(object): def kthPalindrome(self, queries, intLength): """ :type queries: List[int] :type intLength: int :rtype: List[int] """ def g(q, d): if d == 1: return q if q < 10 else -1 m, t = 1, d / 2 - 1 while t > 0: t, m = t - 1, m * 10 u = m * 9 * (10 if d % 2 == 1 else 1) if q > u: return -1 f, r = m + ((q - 1) / 10 if d % 2 == 1 else q - 1), (m + ((q - 1) / 10 if d % 2 == 1 else q - 1)) * 10 + (q - 1) % 10 if d % 2 == 1 else m + ((q - 1) / 10 if d % 2 == 1 else q - 1) while f > 0: r, f = r * 10 + f % 10, f / 10 return r r = [0] * len(queries) for i in range(len(queries)): r[i] = g(queries[i], intLength) return r
343fd8
5070cf
Given an integer array queries and a positive integer intLength, return an array answer where answer[i] is either the queries[i]th smallest positive palindrome of length intLength or -1 if no such palindrome exists. A palindrome is a number that reads the same backwards and forwards. Palindromes cannot have leading zeros.   Example 1: Input: queries = [1,2,3,4,5,90], intLength = 3 Output: [101,111,121,131,141,999] Explanation: The first few palindromes of length 3 are: 101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, ... The 90th palindrome of length 3 is 999. Example 2: Input: queries = [2,4,6], intLength = 4 Output: [1111,1331,1551] Explanation: The first six palindromes of length 4 are: 1001, 1111, 1221, 1331, 1441, and 1551.   Constraints: 1 <= queries.length <= 5 * 10000 1 <= queries[i] <= 10^9 1 <= intLength <= 15
class Solution: def kthPalindrome(self, queries: List[int], intLength: int) -> List[int]: res = [] for i in queries: n = (intLength+1)//2 if 9*10**(n-1) < i: res.append(-1) else: first = (10**(n-1)-1) + i f = str(first) if intLength&1: res.append(int(f+f[:-1][::-1])) else: res.append(int(f+f[::-1])) return res
9e71b8
9e5c5f
Given a list of words, list of  single letters (might be repeating) and score of every character. Return the maximum score of any valid set of words formed by using the given letters (words[i] cannot be used two or more times). It is not necessary to use all characters in letters and each letter can only be used once. Score of letters 'a', 'b', 'c', ... ,'z' is given by score[0], score[1], ... , score[25] respectively.   Example 1: Input: words = ["dog","cat","dad","good"], letters = ["a","a","c","d","d","d","g","o","o"], score = [1,0,9,5,0,0,3,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0] Output: 23 Explanation: Score a=1, c=9, d=5, g=3, o=2 Given letters, we can form the words "dad" (5+1+5) and "good" (3+2+2+5) with a score of 23. Words "dad" and "dog" only get a score of 21. Example 2: Input: words = ["xxxz","ax","bx","cx"], letters = ["z","a","b","c","x","x","x"], score = [4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,10] Output: 27 Explanation: Score a=4, b=4, c=4, x=5, z=10 Given letters, we can form the words "ax" (4+5), "bx" (4+5) and "cx" (4+5) with a score of 27. Word "xxxz" only get a score of 25. Example 3: Input: words = ["leetcode"], letters = ["l","e","t","c","o","d"], score = [0,0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0] Output: 0 Explanation: Letter "e" can only be used once.   Constraints: 1 <= words.length <= 14 1 <= words[i].length <= 15 1 <= letters.length <= 100 letters[i].length == 1 score.length == 26 0 <= score[i] <= 10 words[i], letters[i] contains only lower case English letters.
class Solution(object): def maxScoreWords(self, words, letters, SCORE): def cvt(word): ans = [0] * 26 for letter in word: i = ord(letter) - ord('a') ans[i] += 1 return ans def score(count): ans = 0 for i, c in enumerate(count): ans += c * SCORE[i] return ans words = map(cvt, words) letters = cvt(letters) wordscores = map(score, words) ans = 0 N = len(words) for sz in xrange(N + 1): for cand in itertools.combinations(xrange(N), sz): bns = sum(wordscores[i] for i in cand) if bns <= ans: continue # is it possible count = letters[:] for i in cand: for j, c in enumerate(words[i]): count[j] -= c if all(c >= 0 for c in count): ans = bns return ans
cf0a77
9e5c5f
Given a list of words, list of  single letters (might be repeating) and score of every character. Return the maximum score of any valid set of words formed by using the given letters (words[i] cannot be used two or more times). It is not necessary to use all characters in letters and each letter can only be used once. Score of letters 'a', 'b', 'c', ... ,'z' is given by score[0], score[1], ... , score[25] respectively.   Example 1: Input: words = ["dog","cat","dad","good"], letters = ["a","a","c","d","d","d","g","o","o"], score = [1,0,9,5,0,0,3,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0] Output: 23 Explanation: Score a=1, c=9, d=5, g=3, o=2 Given letters, we can form the words "dad" (5+1+5) and "good" (3+2+2+5) with a score of 23. Words "dad" and "dog" only get a score of 21. Example 2: Input: words = ["xxxz","ax","bx","cx"], letters = ["z","a","b","c","x","x","x"], score = [4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,10] Output: 27 Explanation: Score a=4, b=4, c=4, x=5, z=10 Given letters, we can form the words "ax" (4+5), "bx" (4+5) and "cx" (4+5) with a score of 27. Word "xxxz" only get a score of 25. Example 3: Input: words = ["leetcode"], letters = ["l","e","t","c","o","d"], score = [0,0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0] Output: 0 Explanation: Letter "e" can only be used once.   Constraints: 1 <= words.length <= 14 1 <= words[i].length <= 15 1 <= letters.length <= 100 letters[i].length == 1 score.length == 26 0 <= score[i] <= 10 words[i], letters[i] contains only lower case English letters.
class Solution: maxs=0 n=0 def cal(self,newdic,dic,s,step,score): if step==self.n: self.maxs=max(self.maxs,s) return flag=True nows=0 for i in range(26): dic[i]=dic[i]-newdic[step][i] nows=nows+score[i]*newdic[step][i] if dic[i]<0: flag=False if flag==True: self.cal(newdic,dic,s+nows,step+1,score) for i in range(26): dic[i]=dic[i]+newdic[step][i] self.cal(newdic,dic,s,step+1,score) def maxScoreWords(self, words: List[str], letters: List[str], score: List[int]) -> int: self.maxs=0 self.n=len(words) dic=[0 for i in range(26)] newdic=[[0 for i in range(26)] for j in range(len(words))] for x in letters: dic[ord(x)-ord('a')]+=1 for i in range(len(words)): word=words[i] for x in word: newdic[i][ord(x)-ord('a')]+=1 self.cal(newdic,dic,0,0,score) return self.maxs
d19a32
0d2f2d
You are given a 0-indexed integer array nums of size n and a positive integer k. We call an index i in the range k <= i < n - k good if the following conditions are satisfied: The k elements that are just before the index i are in non-increasing order. The k elements that are just after the index i are in non-decreasing order. Return an array of all good indices sorted in increasing order.   Example 1: Input: nums = [2,1,1,1,3,4,1], k = 2 Output: [2,3] Explanation: There are two good indices in the array: - Index 2. The subarray [2,1] is in non-increasing order, and the subarray [1,3] is in non-decreasing order. - Index 3. The subarray [1,1] is in non-increasing order, and the subarray [3,4] is in non-decreasing order. Note that the index 4 is not good because [4,1] is not non-decreasing. Example 2: Input: nums = [2,1,1,2], k = 2 Output: [] Explanation: There are no good indices in this array.   Constraints: n == nums.length 3 <= n <= 100000 1 <= nums[i] <= 1000000 1 <= k <= n / 2
class Solution: def goodIndices(self, nums: List[int], k: int) -> List[int]: n = len(nums) bef = [1]*n after = [1]*n for i in range(1, n): if nums[i] <= nums[i-1]: bef[i] = bef[i-1]+1 for i in range(n-2, -1, -1): if nums[i] <= nums[i+1]: after[i] = after[i+1]+1 res = [] for i in range(k, n-k): if bef[i-1] >= k and after[i+1] >= k: res.append(i) return res
bd769a
0d2f2d
You are given a 0-indexed integer array nums of size n and a positive integer k. We call an index i in the range k <= i < n - k good if the following conditions are satisfied: The k elements that are just before the index i are in non-increasing order. The k elements that are just after the index i are in non-decreasing order. Return an array of all good indices sorted in increasing order.   Example 1: Input: nums = [2,1,1,1,3,4,1], k = 2 Output: [2,3] Explanation: There are two good indices in the array: - Index 2. The subarray [2,1] is in non-increasing order, and the subarray [1,3] is in non-decreasing order. - Index 3. The subarray [1,1] is in non-increasing order, and the subarray [3,4] is in non-decreasing order. Note that the index 4 is not good because [4,1] is not non-decreasing. Example 2: Input: nums = [2,1,1,2], k = 2 Output: [] Explanation: There are no good indices in this array.   Constraints: n == nums.length 3 <= n <= 100000 1 <= nums[i] <= 1000000 1 <= k <= n / 2
class Solution(object): def goodIndices(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ g, h, r, s, t = [False] * len(nums), [False] * len(nums), 1, 1, [] for i in range(1, len(nums)): g[i], r = r >= k, 1 if nums[i] > nums[i - 1] else r + 1 for i in range(len(nums) - 2, -1, -1): h[i], s = s >= k, 1 if nums[i] > nums[i + 1] else s + 1 for i in range(len(nums)): if g[i] and h[i]: t.append(i) return t
9a7336
5b637f
Given a string word to which you can insert letters "a", "b" or "c" anywhere and any number of times, return the minimum number of letters that must be inserted so that word becomes valid. A string is called valid if it can be formed by concatenating the string "abc" several times.   Example 1: Input: word = "b" Output: 2 Explanation: Insert the letter "a" right before "b", and the letter "c" right next to "a" to obtain the valid string "abc". Example 2: Input: word = "aaa" Output: 6 Explanation: Insert letters "b" and "c" next to each "a" to obtain the valid string "abcabcabc". Example 3: Input: word = "abc" Output: 0 Explanation: word is already valid. No modifications are needed.   Constraints: 1 <= word.length <= 50 word consists of letters "a", "b" and "c" only. 
abc = 'abc' class Solution: def addMinimum(self, word: str) -> int: cnt = 0 pos = 2 for c in word: idx = abc.index(c) if idx > pos: pos = idx else: pos = idx cnt += 1 return 3 * cnt - len(word)
e35033
5b637f
Given a string word to which you can insert letters "a", "b" or "c" anywhere and any number of times, return the minimum number of letters that must be inserted so that word becomes valid. A string is called valid if it can be formed by concatenating the string "abc" several times.   Example 1: Input: word = "b" Output: 2 Explanation: Insert the letter "a" right before "b", and the letter "c" right next to "a" to obtain the valid string "abc". Example 2: Input: word = "aaa" Output: 6 Explanation: Insert letters "b" and "c" next to each "a" to obtain the valid string "abcabcabc". Example 3: Input: word = "abc" Output: 0 Explanation: word is already valid. No modifications are needed.   Constraints: 1 <= word.length <= 50 word consists of letters "a", "b" and "c" only. 
class Solution(object): def addMinimum(self, word): """ :type word: str :rtype: int """ r, i = 0, 0 while i < len(word): if word[i] == 'a': if i + 1 < len(word) and word[i + 1] == 'b': if i + 2 < len(word) and word[i + 2] == 'c': i += 3 else: r, i = r + 1, i + 2 elif i + 1 < len(word) and word[i + 1] == 'c': r, i = r + 1, i + 2 else: r, i = r + 2, i + 1 elif word[i] == 'b': r += 1 if i + 1 < len(word) and word[i + 1] == 'c': i += 2 else: r, i = r + 1, i + 1 else: r, i = r + 2, i + 1 return r
ca6514
742851
There is an ATM machine that stores banknotes of 5 denominations: 20, 50, 100, 200, and 500 dollars. Initially the ATM is empty. The user can use the machine to deposit or withdraw any amount of money. When withdrawing, the machine prioritizes using banknotes of larger values. For example, if you want to withdraw $300 and there are 2 $50 banknotes, 1 $100 banknote, and 1 $200 banknote, then the machine will use the $100 and $200 banknotes. However, if you try to withdraw $600 and there are 3 $200 banknotes and 1 $500 banknote, then the withdraw request will be rejected because the machine will first try to use the $500 banknote and then be unable to use banknotes to complete the remaining $100. Note that the machine is not allowed to use the $200 banknotes instead of the $500 banknote. Implement the ATM class: ATM() Initializes the ATM object. void deposit(int[] banknotesCount) Deposits new banknotes in the order $20, $50, $100, $200, and $500. int[] withdraw(int amount) Returns an array of length 5 of the number of banknotes that will be handed to the user in the order $20, $50, $100, $200, and $500, and update the number of banknotes in the ATM after withdrawing. Returns [-1] if it is not possible (do not withdraw any banknotes in this case).   Example 1: Input ["ATM", "deposit", "withdraw", "deposit", "withdraw", "withdraw"] [[], [[0,0,1,2,1]], [600], [[0,1,0,1,1]], [600], [550]] Output [null, null, [0,0,1,0,1], null, [-1], [0,1,0,0,1]] Explanation ATM atm = new ATM(); atm.deposit([0,0,1,2,1]); // Deposits 1 $100 banknote, 2 $200 banknotes, // and 1 $500 banknote. atm.withdraw(600); // Returns [0,0,1,0,1]. The machine uses 1 $100 banknote // and 1 $500 banknote. The banknotes left over in the // machine are [0,0,0,2,0]. atm.deposit([0,1,0,1,1]); // Deposits 1 $50, $200, and $500 banknote. // The banknotes in the machine are now [0,1,0,3,1]. atm.withdraw(600); // Returns [-1]. The machine will try to use a $500 banknote // and then be unable to complete the remaining $100, // so the withdraw request will be rejected. // Since the request is rejected, the number of banknotes // in the machine is not modified. atm.withdraw(550); // Returns [0,1,0,0,1]. The machine uses 1 $50 banknote // and 1 $500 banknote.   Constraints: banknotesCount.length == 5 0 <= banknotesCount[i] <= 10^9 1 <= amount <= 10^9 At most 5000 calls in total will be made to withdraw and deposit. At least one call will be made to each function withdraw and deposit.
class ATM: def __init__(self): self.notes = [0]*5 def deposit(self, banknotesCount: List[int]) -> None: for idx, i in enumerate(banknotesCount): self.notes[idx] += i def withdraw(self, amount: int) -> List[int]: amt = amount ans = [0]*5 ci = 4 for c, d in zip(self.notes[::-1], [20, 50, 100, 200, 500][::-1]): # print(ans, amt) cc = min(c, amt//d) ans[ci] = cc amt -= cc*d ci -= 1 qq = 0 for c, d in zip(ans, [20, 50, 100, 200, 500]): qq += c*d if qq == amount: for idx, i in enumerate(ans): self.notes[idx] -= i return ans return [-1] # Your ATM object will be instantiated and called as such: # obj = ATM() # obj.deposit(banknotesCount) # param_2 = obj.withdraw(amount)
d5b7dc
742851
There is an ATM machine that stores banknotes of 5 denominations: 20, 50, 100, 200, and 500 dollars. Initially the ATM is empty. The user can use the machine to deposit or withdraw any amount of money. When withdrawing, the machine prioritizes using banknotes of larger values. For example, if you want to withdraw $300 and there are 2 $50 banknotes, 1 $100 banknote, and 1 $200 banknote, then the machine will use the $100 and $200 banknotes. However, if you try to withdraw $600 and there are 3 $200 banknotes and 1 $500 banknote, then the withdraw request will be rejected because the machine will first try to use the $500 banknote and then be unable to use banknotes to complete the remaining $100. Note that the machine is not allowed to use the $200 banknotes instead of the $500 banknote. Implement the ATM class: ATM() Initializes the ATM object. void deposit(int[] banknotesCount) Deposits new banknotes in the order $20, $50, $100, $200, and $500. int[] withdraw(int amount) Returns an array of length 5 of the number of banknotes that will be handed to the user in the order $20, $50, $100, $200, and $500, and update the number of banknotes in the ATM after withdrawing. Returns [-1] if it is not possible (do not withdraw any banknotes in this case).   Example 1: Input ["ATM", "deposit", "withdraw", "deposit", "withdraw", "withdraw"] [[], [[0,0,1,2,1]], [600], [[0,1,0,1,1]], [600], [550]] Output [null, null, [0,0,1,0,1], null, [-1], [0,1,0,0,1]] Explanation ATM atm = new ATM(); atm.deposit([0,0,1,2,1]); // Deposits 1 $100 banknote, 2 $200 banknotes, // and 1 $500 banknote. atm.withdraw(600); // Returns [0,0,1,0,1]. The machine uses 1 $100 banknote // and 1 $500 banknote. The banknotes left over in the // machine are [0,0,0,2,0]. atm.deposit([0,1,0,1,1]); // Deposits 1 $50, $200, and $500 banknote. // The banknotes in the machine are now [0,1,0,3,1]. atm.withdraw(600); // Returns [-1]. The machine will try to use a $500 banknote // and then be unable to complete the remaining $100, // so the withdraw request will be rejected. // Since the request is rejected, the number of banknotes // in the machine is not modified. atm.withdraw(550); // Returns [0,1,0,0,1]. The machine uses 1 $50 banknote // and 1 $500 banknote.   Constraints: banknotesCount.length == 5 0 <= banknotesCount[i] <= 10^9 1 <= amount <= 10^9 At most 5000 calls in total will be made to withdraw and deposit. At least one call will be made to each function withdraw and deposit.
class ATM(object): def __init__(self): self.cs = [0]*5 def deposit(self, banknotesCount): """ :type banknotesCount: List[int] :rtype: None """ for i in range(5): self.cs[i]+=banknotesCount[i] def withdraw(self, amount): """ :type amount: int :rtype: List[int] """ ns = [0]*5 cc = (20, 50, 100, 200, 500) k=4 while k>=0: c=self.cs[k] nc=amount/cc[k] if nc>c: nc=c ns[k]=nc amount-=nc*cc[k] k-=1 if amount: return [-1] for k in range(5): self.cs[k]-=ns[k] return ns # Your ATM object will be instantiated and called as such: # obj = ATM() # obj.deposit(banknotesCount) # param_2 = obj.withdraw(amount)
4ee593
0c865c
There is a directed graph of n nodes with each node labeled from 0 to n - 1. The graph is represented by a 0-indexed 2D integer array graph where graph[i] is an integer array of nodes adjacent to node i, meaning there is an edge from node i to each node in graph[i]. A node is a terminal node if there are no outgoing edges. A node is a safe node if every possible path starting from that node leads to a terminal node (or another safe node). Return an array containing all the safe nodes of the graph. The answer should be sorted in ascending order.   Example 1: Input: graph = [[1,2],[2,3],[5],[0],[5],[],[]] Output: [2,4,5,6] Explanation: The given graph is shown above. Nodes 5 and 6 are terminal nodes as there are no outgoing edges from either of them. Every path starting at nodes 2, 4, 5, and 6 all lead to either node 5 or 6. Example 2: Input: graph = [[1,2,3,4],[1,2],[3,4],[0,4],[]] Output: [4] Explanation: Only node 4 is a terminal node, and every path starting at node 4 leads to node 4.   Constraints: n == graph.length 1 <= n <= 10000 0 <= graph[i].length <= n 0 <= graph[i][j] <= n - 1 graph[i] is sorted in a strictly increasing order. The graph may contain self-loops. The number of edges in the graph will be in the range [1, 4 * 10000].
class Solution(object): def eventualSafeNodes(self, graph): res = [] count = {i: 0 for i in range(len(graph))} for i, edges in enumerate(graph): count[i] = len(edges) zeroes = [j for j in range(len(graph)) if count[j] == 0] graph2 = [[] for _ in graph] for i, edges in enumerate(graph): for j in edges: graph2[j].append(i) while zeroes: node = zeroes.pop() res.append(node) for prev in graph2[node]: count[prev] -= 1 if count[prev] == 0: zeroes.append(prev) return sorted(res)
a4d7de
0c865c
There is a directed graph of n nodes with each node labeled from 0 to n - 1. The graph is represented by a 0-indexed 2D integer array graph where graph[i] is an integer array of nodes adjacent to node i, meaning there is an edge from node i to each node in graph[i]. A node is a terminal node if there are no outgoing edges. A node is a safe node if every possible path starting from that node leads to a terminal node (or another safe node). Return an array containing all the safe nodes of the graph. The answer should be sorted in ascending order.   Example 1: Input: graph = [[1,2],[2,3],[5],[0],[5],[],[]] Output: [2,4,5,6] Explanation: The given graph is shown above. Nodes 5 and 6 are terminal nodes as there are no outgoing edges from either of them. Every path starting at nodes 2, 4, 5, and 6 all lead to either node 5 or 6. Example 2: Input: graph = [[1,2,3,4],[1,2],[3,4],[0,4],[]] Output: [4] Explanation: Only node 4 is a terminal node, and every path starting at node 4 leads to node 4.   Constraints: n == graph.length 1 <= n <= 10000 0 <= graph[i].length <= n 0 <= graph[i][j] <= n - 1 graph[i] is sorted in a strictly increasing order. The graph may contain self-loops. The number of edges in the graph will be in the range [1, 4 * 10000].
class Solution(object): def dfs(self, u, graph, instk, vis): instk[u] = 1 vis[u] = 1 for v in graph[u]: if instk[v] or vis[v] == 2: vis[u] = 2 elif vis[v] == 0: self.dfs(v, graph, instk, vis) if vis[v] == 2: vis[u] = 2 instk[u] = 0 return vis[u] def eventualSafeNodes(self, graph): """ :type graph: List[List[int]] :rtype: List[int] """ vis = [0]*len(graph) instk = [0]*len(graph) for i in range(len(graph)): self.dfs(i, graph, instk, vis) ans = [] for i in range(len(graph)): if vis[i] != 2: ans += [i] return ans
fe9f5b
52ddfa
In a warehouse, there is a row of barcodes, where the ith barcode is barcodes[i]. Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists.   Example 1: Input: barcodes = [1,1,1,2,2,2] Output: [2,1,2,1,2,1] Example 2: Input: barcodes = [1,1,1,1,2,2,3,3] Output: [1,3,1,3,1,2,1,2]   Constraints: 1 <= barcodes.length <= 10000 1 <= barcodes[i] <= 10000
class Solution: def rearrangeBarcodes(self, barcodes: List[int]) -> List[int]: n = len(barcodes) idxes = collections.deque(list(range(0, n, 2)) + list(range(1, n, 2))) counter = collections.Counter(barcodes) ans = [None] * n for num, cnt in counter.most_common(): for _ in range(cnt): ans[idxes.popleft()] = num return ans
e9c17f
52ddfa
In a warehouse, there is a row of barcodes, where the ith barcode is barcodes[i]. Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists.   Example 1: Input: barcodes = [1,1,1,2,2,2] Output: [2,1,2,1,2,1] Example 2: Input: barcodes = [1,1,1,1,2,2,3,3] Output: [1,3,1,3,1,2,1,2]   Constraints: 1 <= barcodes.length <= 10000 1 <= barcodes[i] <= 10000
from collections import Counter class Solution(object): def rearrangeBarcodes(self, barcodes): """ :type barcodes: List[int] :rtype: List[int] """ n = len(barcodes) r = [None for _ in xrange(n)] i = 0 for v, c in Counter(barcodes).most_common(): for _ in xrange(c): while r[i] is not None: i = (i + 1) % n r[i] = v i = (i + 2) % n return r
dc7bf2
6d5ab6
Given an array nums of positive integers. Your task is to select some subset of nums, multiply each element by an integer and add all these numbers. The array is said to be good if you can obtain a sum of 1 from the array by any possible subset and multiplicand. Return True if the array is good otherwise return False.   Example 1: Input: nums = [12,5,7,23] Output: true Explanation: Pick numbers 5 and 7. 5*3 + 7*(-2) = 1 Example 2: Input: nums = [29,6,10] Output: true Explanation: Pick numbers 29, 6 and 10. 29*1 + 6*(-3) + 10*(-1) = 1 Example 3: Input: nums = [3,6] Output: false   Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9
from fractions import gcd class Solution(object): def isGoodArray(self, nums): """ :type nums: List[int] :rtype: bool """ return reduce(gcd, nums, 0) == 1
607ee1
6d5ab6
Given an array nums of positive integers. Your task is to select some subset of nums, multiply each element by an integer and add all these numbers. The array is said to be good if you can obtain a sum of 1 from the array by any possible subset and multiplicand. Return True if the array is good otherwise return False.   Example 1: Input: nums = [12,5,7,23] Output: true Explanation: Pick numbers 5 and 7. 5*3 + 7*(-2) = 1 Example 2: Input: nums = [29,6,10] Output: true Explanation: Pick numbers 29, 6 and 10. 29*1 + 6*(-3) + 10*(-1) = 1 Example 3: Input: nums = [3,6] Output: false   Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9
class Solution: def isGoodArray(self, nums: List[int]) -> bool: res=nums[0] for i in nums: res=math.gcd(res,i) return abs(res)==1
c0c207
475762
You are given a m x n matrix grid. Initially, you are located at the top-left corner (0, 0), and in each step, you can only move right or down in the matrix. Among all possible paths starting from the top-left corner (0, 0) and ending in the bottom-right corner (m - 1, n - 1), find the path with the maximum non-negative product. The product of a path is the product of all integers in the grid cells visited along the path. Return the maximum non-negative product modulo 10^9 + 7. If the maximum product is negative, return -1. Notice that the modulo is performed after getting the maximum product.   Example 1: Input: grid = [[-1,-2,-3],[-2,-3,-3],[-3,-3,-2]] Output: -1 Explanation: It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1. Example 2: Input: grid = [[1,-2,1],[1,-2,1],[3,-4,1]] Output: 8 Explanation: Maximum non-negative product is shown (1 * 1 * -2 * -4 * 1 = 8). Example 3: Input: grid = [[1,3],[0,-4]] Output: 0 Explanation: Maximum non-negative product is shown (1 * 0 * -4 = 0).   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 15 -4 <= grid[i][j] <= 4
class Solution: def maxProductPath(self, grid: List[List[int]]) -> int: dp=[[None]*len(grid[0]) for _ in range(len(grid))] dp[0][0]=[grid[0][0],grid[0][0]] for j in range(1,len(grid[0])): val=grid[0][j]*dp[0][j-1][0] dp[0][j]=[val,val] for i in range(1,len(grid)): val=grid[i][0]*dp[i-1][0][0] dp[i][0]=[val,val] for i in range(1,len(grid)): for j in range(1,len(grid[0])): mn=min(dp[i-1][j][0]*grid[i][j],dp[i][j-1][0]*grid[i][j],dp[i-1][j][1]*grid[i][j],dp[i][j-1][1]*grid[i][j]) mx=max(dp[i-1][j][0]*grid[i][j],dp[i][j-1][0]*grid[i][j],dp[i-1][j][1]*grid[i][j],dp[i][j-1][1]*grid[i][j]) dp[i][j]=[mn,mx] ret=dp[-1][-1][1] if ret<0: return -1 return ret%(10**9+7)
a455a3
475762
You are given a m x n matrix grid. Initially, you are located at the top-left corner (0, 0), and in each step, you can only move right or down in the matrix. Among all possible paths starting from the top-left corner (0, 0) and ending in the bottom-right corner (m - 1, n - 1), find the path with the maximum non-negative product. The product of a path is the product of all integers in the grid cells visited along the path. Return the maximum non-negative product modulo 10^9 + 7. If the maximum product is negative, return -1. Notice that the modulo is performed after getting the maximum product.   Example 1: Input: grid = [[-1,-2,-3],[-2,-3,-3],[-3,-3,-2]] Output: -1 Explanation: It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1. Example 2: Input: grid = [[1,-2,1],[1,-2,1],[3,-4,1]] Output: 8 Explanation: Maximum non-negative product is shown (1 * 1 * -2 * -4 * 1 = 8). Example 3: Input: grid = [[1,3],[0,-4]] Output: 0 Explanation: Maximum non-negative product is shown (1 * 0 * -4 = 0).   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 15 -4 <= grid[i][j] <= 4
class Solution(object): def maxProductPath(self, grid): """ :type grid: List[List[int]] :rtype: int """ mod = 10**9+7 m,n = len(grid),len(grid[0]) dpmin = [[1 for _ in range(n)] for _ in range(m)] dpmax = [[1 for _ in range(n)] for _ in range(m)] dpmin[0][0] = grid[0][0] dpmax[0][0] = grid[0][0] for i in range(m-1): dpmin[i+1][0] = dpmin[i][0]*grid[i+1][0] dpmax[i+1][0] = dpmax[i][0]*grid[i+1][0] for j in range(n-1): dpmin[0][j+1] = dpmin[0][j]*grid[0][j+1] dpmax[0][j+1] = dpmax[0][j]*grid[0][j+1] for i in range(m-1): for j in range(n-1): dpmin[i+1][j+1] = min(dpmin[i+1][j]*grid[i+1][j+1],dpmax[i+1][j]*grid[i+1][j+1],dpmin[i][j+1]*grid[i+1][j+1],dpmax[i][j+1]*grid[i+1][j+1]) dpmax[i+1][j+1] = max(dpmin[i+1][j]*grid[i+1][j+1],dpmax[i+1][j]*grid[i+1][j+1],dpmin[i][j+1]*grid[i+1][j+1],dpmax[i][j+1]*grid[i+1][j+1]) # print(dpmax) # print(dpmin) return dpmax[-1][-1]%mod if dpmax[-1][-1]>=0 else -1
c60d12
892dbe
A farmer has a rectangular grid of land with m rows and n columns that can be divided into unit cells. Each cell is either fertile (represented by a 1) or barren (represented by a 0). All cells outside the grid are considered barren. A pyramidal plot of land can be defined as a set of cells with the following criteria: The number of cells in the set has to be greater than 1 and all cells must be fertile. The apex of a pyramid is the topmost cell of the pyramid. The height of a pyramid is the number of rows it covers. Let (r, c) be the apex of the pyramid, and its height be h. Then, the plot comprises of cells (i, j) where r <= i <= r + h - 1 and c - (i - r) <= j <= c + (i - r). An inverse pyramidal plot of land can be defined as a set of cells with similar criteria: The number of cells in the set has to be greater than 1 and all cells must be fertile. The apex of an inverse pyramid is the bottommost cell of the inverse pyramid. The height of an inverse pyramid is the number of rows it covers. Let (r, c) be the apex of the pyramid, and its height be h. Then, the plot comprises of cells (i, j) where r - h + 1 <= i <= r and c - (r - i) <= j <= c + (r - i). Some examples of valid and invalid pyramidal (and inverse pyramidal) plots are shown below. Black cells indicate fertile cells. Given a 0-indexed m x n binary matrix grid representing the farmland, return the total number of pyramidal and inverse pyramidal plots that can be found in grid.   Example 1: Input: grid = [[0,1,1,0],[1,1,1,1]] Output: 2 Explanation: The 2 possible pyramidal plots are shown in blue and red respectively. There are no inverse pyramidal plots in this grid. Hence total number of pyramidal and inverse pyramidal plots is 2 + 0 = 2. Example 2: Input: grid = [[1,1,1],[1,1,1]] Output: 2 Explanation: The pyramidal plot is shown in blue, and the inverse pyramidal plot is shown in red. Hence the total number of plots is 1 + 1 = 2. Example 3: Input: grid = [[1,1,1,1,0],[1,1,1,1,1],[1,1,1,1,1],[0,1,0,0,1]] Output: 13 Explanation: There are 7 pyramidal plots, 3 of which are shown in the 2nd and 3rd figures. There are 6 inverse pyramidal plots, 2 of which are shown in the last figure. The total number of plots is 7 + 6 = 13.   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 1000 1 <= m * n <= 100000 grid[i][j] is either 0 or 1.
class Solution: def countPyramids(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) pre_sum = [] for line in grid : lt = [0] for t in line : lt.append(lt[-1]+t) pre_sum.append(lt) to_ret = 0 for i in range(m) : for j in range(n) : if not grid[i][j] == 1 : continue for h1 in range(1, 99999) : if i+h1 >= m or j+h1 >= n or j-h1 < 0: break if not pre_sum[i+h1][j+h1+1] - pre_sum[i+h1][j-h1] == 2*h1+1: break to_ret += 1 for h1 in range(1, 99999) : if i-h1 < 0 or j+h1 >= n or j-h1 < 0: break if not pre_sum[i-h1][j+h1+1] - pre_sum[i-h1][j-h1] == 2*h1+1: break to_ret += 1 return to_ret
88b985
892dbe
A farmer has a rectangular grid of land with m rows and n columns that can be divided into unit cells. Each cell is either fertile (represented by a 1) or barren (represented by a 0). All cells outside the grid are considered barren. A pyramidal plot of land can be defined as a set of cells with the following criteria: The number of cells in the set has to be greater than 1 and all cells must be fertile. The apex of a pyramid is the topmost cell of the pyramid. The height of a pyramid is the number of rows it covers. Let (r, c) be the apex of the pyramid, and its height be h. Then, the plot comprises of cells (i, j) where r <= i <= r + h - 1 and c - (i - r) <= j <= c + (i - r). An inverse pyramidal plot of land can be defined as a set of cells with similar criteria: The number of cells in the set has to be greater than 1 and all cells must be fertile. The apex of an inverse pyramid is the bottommost cell of the inverse pyramid. The height of an inverse pyramid is the number of rows it covers. Let (r, c) be the apex of the pyramid, and its height be h. Then, the plot comprises of cells (i, j) where r - h + 1 <= i <= r and c - (r - i) <= j <= c + (r - i). Some examples of valid and invalid pyramidal (and inverse pyramidal) plots are shown below. Black cells indicate fertile cells. Given a 0-indexed m x n binary matrix grid representing the farmland, return the total number of pyramidal and inverse pyramidal plots that can be found in grid.   Example 1: Input: grid = [[0,1,1,0],[1,1,1,1]] Output: 2 Explanation: The 2 possible pyramidal plots are shown in blue and red respectively. There are no inverse pyramidal plots in this grid. Hence total number of pyramidal and inverse pyramidal plots is 2 + 0 = 2. Example 2: Input: grid = [[1,1,1],[1,1,1]] Output: 2 Explanation: The pyramidal plot is shown in blue, and the inverse pyramidal plot is shown in red. Hence the total number of plots is 1 + 1 = 2. Example 3: Input: grid = [[1,1,1,1,0],[1,1,1,1,1],[1,1,1,1,1],[0,1,0,0,1]] Output: 13 Explanation: There are 7 pyramidal plots, 3 of which are shown in the 2nd and 3rd figures. There are 6 inverse pyramidal plots, 2 of which are shown in the last figure. The total number of plots is 7 + 6 = 13.   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 1000 1 <= m * n <= 100000 grid[i][j] is either 0 or 1.
class Solution(object): def countPyramids(self, grid): """ :type grid: List[List[int]] :rtype: int """ ans = 0 m = len(grid) n = len(grid[0]) go_left = [[0 for c in range(n)] for r in range(m)] go_right = [[0 for c in range(n)] for r in range(m)] for r in range(m): go_left[r][0] = grid[r][0] for c in range(1, n): go_left[r][c] = (0 if grid[r][c] == 0 else go_left[r][c - 1] + 1) go_right[r][n - 1] = grid[r][n - 1] for c in range(n - 2, -1, -1): go_right[r][c] = (0 if grid[r][c] == 0 else go_right[r][c + 1] + 1) for c in range(n): nr = 0 for r in range(m): while nr < m and min(go_left[nr][c], go_right[nr][c]) >= nr - r + 1: nr += 1 if nr - r >= 2: ans += (nr - r - 1) nr = m - 1 for r in range(m - 1, -1, -1): while nr >= 0 and min(go_left[nr][c], go_right[nr][c]) >= r - nr + 1: nr -= 1 if r - nr >= 2: ans += (r - nr - 1) return ans
925271
052f4b
Given a string s, encode the string such that its encoded length is the shortest. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. k should be a positive integer. If an encoding process does not make the string shorter, then do not encode it. If there are several solutions, return any of them. Example 1: Input: s = "aaa" Output: "aaa" Explanation: There is no way to encode it such that it is shorter than the input string, so we do not encode it. Example 2: Input: s = "aaaaa" Output: "5[a]" Explanation: "5[a]" is shorter than "aaaaa" by 1 character. Example 3: Input: s = "aaaaaaaaaa" Output: "10[a]" Explanation: "a9[a]" or "9[a]a" are also valid solutions, both of them have the same length = 5, which is the same as "10[a]". Constraints: 1 <= s.length <= 150 s consists of only lowercase English letters.
class Solution(object): def calc(self, f, s): n = len(s) if n == 0: return '' if s in f: return f[s] ret = s tmp = s[0] + self.calc(f, s[1:]) if len(ret) > len(tmp): ret = tmp for l in range(1, n/2+1): k = 1 while True: tmp = str(k) + '[' + self.calc(f, s[:l]) + ']' + self.calc(f, s[l*k:]) if len(ret) > len(tmp): ret = tmp if (k+1)*l > n: break if s[:l] != s[k*l: (k+1)*l]: break k += 1 f[s] = ret return ret def encode(self, s): """ :type s: str :rtype: str """ f = {} return self.calc(f, s)
974c7c
a85537
There is a network of n servers, labeled from 0 to n - 1. You are given a 2D integer array edges, where edges[i] = [ui, vi] indicates there is a message channel between servers ui and vi, and they can pass any number of messages to each other directly in one second. You are also given a 0-indexed integer array patience of length n. All servers are connected, i.e., a message can be passed from one server to any other server(s) directly or indirectly through the message channels. The server labeled 0 is the master server. The rest are data servers. Each data server needs to send its message to the master server for processing and wait for a reply. Messages move between servers optimally, so every message takes the least amount of time to arrive at the master server. The master server will process all newly arrived messages instantly and send a reply to the originating server via the reversed path the message had gone through. At the beginning of second 0, each data server sends its message to be processed. Starting from second 1, at the beginning of every second, each data server will check if it has received a reply to the message it sent (including any newly arrived replies) from the master server: If it has not, it will resend the message periodically. The data server i will resend the message every patience[i] second(s), i.e., the data server i will resend the message if patience[i] second(s) have elapsed since the last time the message was sent from this server. Otherwise, no more resending will occur from this server. The network becomes idle when there are no messages passing between servers or arriving at servers. Return the earliest second starting from which the network becomes idle.   Example 1: Input: edges = [[0,1],[1,2]], patience = [0,2,1] Output: 8 Explanation: At (the beginning of) second 0, - Data server 1 sends its message (denoted 1A) to the master server. - Data server 2 sends its message (denoted 2A) to the master server. At second 1, - Message 1A arrives at the master server. Master server processes message 1A instantly and sends a reply 1A back. - Server 1 has not received any reply. 1 second (1 < patience[1] = 2) elapsed since this server has sent the message, therefore it does not resend the message. - Server 2 has not received any reply. 1 second (1 == patience[2] = 1) elapsed since this server has sent the message, therefore it resends the message (denoted 2B). At second 2, - The reply 1A arrives at server 1. No more resending will occur from server 1. - Message 2A arrives at the master server. Master server processes message 2A instantly and sends a reply 2A back. - Server 2 resends the message (denoted 2C). ... At second 4, - The reply 2A arrives at server 2. No more resending will occur from server 2. ... At second 7, reply 2D arrives at server 2. Starting from the beginning of the second 8, there are no messages passing between servers or arriving at servers. This is the time when the network becomes idle. Example 2: Input: edges = [[0,1],[0,2],[1,2]], patience = [0,10,10] Output: 3 Explanation: Data servers 1 and 2 receive a reply back at the beginning of second 2. From the beginning of the second 3, the network becomes idle.   Constraints: n == patience.length 2 <= n <= 100000 patience[0] == 0 1 <= patience[i] <= 100000 for 1 <= i < n 1 <= edges.length <= min(100000, n * (n - 1) / 2) edges[i].length == 2 0 <= ui, vi < n ui != vi There are no duplicate edges. Each server can directly or indirectly reach another server.
class Solution: def networkBecomesIdle(self, edges: List[List[int]], patience: List[int]) -> int: n = len(patience) dist = [math.inf for _ in range(n)] dist[0] = 0 graph = [[] for _ in range(n)] for u, v in edges: graph[u].append(v) graph[v].append(u) q = deque([]) q.append(0) while q: u = q.popleft() for v in graph[u]: if dist[u] + 1 < dist[v]: dist[v] = dist[u] + 1 q.append(v) ans = 0 for u in range(1, n): # find the largest t divisible by patience u that is < 2 * dist t = patience[u] * (2 * dist[u] // patience[u]) while t >= 2 * dist[u]: t -= patience[u] while t + patience[u] < 2 * dist[u]: t += patience[u] ans = max(ans, t + 2 * dist[u]) return ans + 1
d771dd
a85537
There is a network of n servers, labeled from 0 to n - 1. You are given a 2D integer array edges, where edges[i] = [ui, vi] indicates there is a message channel between servers ui and vi, and they can pass any number of messages to each other directly in one second. You are also given a 0-indexed integer array patience of length n. All servers are connected, i.e., a message can be passed from one server to any other server(s) directly or indirectly through the message channels. The server labeled 0 is the master server. The rest are data servers. Each data server needs to send its message to the master server for processing and wait for a reply. Messages move between servers optimally, so every message takes the least amount of time to arrive at the master server. The master server will process all newly arrived messages instantly and send a reply to the originating server via the reversed path the message had gone through. At the beginning of second 0, each data server sends its message to be processed. Starting from second 1, at the beginning of every second, each data server will check if it has received a reply to the message it sent (including any newly arrived replies) from the master server: If it has not, it will resend the message periodically. The data server i will resend the message every patience[i] second(s), i.e., the data server i will resend the message if patience[i] second(s) have elapsed since the last time the message was sent from this server. Otherwise, no more resending will occur from this server. The network becomes idle when there are no messages passing between servers or arriving at servers. Return the earliest second starting from which the network becomes idle.   Example 1: Input: edges = [[0,1],[1,2]], patience = [0,2,1] Output: 8 Explanation: At (the beginning of) second 0, - Data server 1 sends its message (denoted 1A) to the master server. - Data server 2 sends its message (denoted 2A) to the master server. At second 1, - Message 1A arrives at the master server. Master server processes message 1A instantly and sends a reply 1A back. - Server 1 has not received any reply. 1 second (1 < patience[1] = 2) elapsed since this server has sent the message, therefore it does not resend the message. - Server 2 has not received any reply. 1 second (1 == patience[2] = 1) elapsed since this server has sent the message, therefore it resends the message (denoted 2B). At second 2, - The reply 1A arrives at server 1. No more resending will occur from server 1. - Message 2A arrives at the master server. Master server processes message 2A instantly and sends a reply 2A back. - Server 2 resends the message (denoted 2C). ... At second 4, - The reply 2A arrives at server 2. No more resending will occur from server 2. ... At second 7, reply 2D arrives at server 2. Starting from the beginning of the second 8, there are no messages passing between servers or arriving at servers. This is the time when the network becomes idle. Example 2: Input: edges = [[0,1],[0,2],[1,2]], patience = [0,10,10] Output: 3 Explanation: Data servers 1 and 2 receive a reply back at the beginning of second 2. From the beginning of the second 3, the network becomes idle.   Constraints: n == patience.length 2 <= n <= 100000 patience[0] == 0 1 <= patience[i] <= 100000 for 1 <= i < n 1 <= edges.length <= min(100000, n * (n - 1) / 2) edges[i].length == 2 0 <= ui, vi < n ui != vi There are no duplicate edges. Each server can directly or indirectly reach another server.
class Solution(object): def networkBecomesIdle(self, edges, patience): """ :type edges: List[List[int]] :type patience: List[int] :rtype: int """ link = {} for i,j in edges: if i not in link: link[i] = set() link[i].add(j) if j not in link: link[j] = set() link[j].add(i) dis = {0:0} has = set([0]) i = 0 wait = [0] while i < len(wait): for j in link[wait[i]]: if j not in has: wait.append(j) has.add(j) dis[j] = dis[wait[i]]+1 i +=1 best = 0 for i in dis: if i!=0: best = max(best,dis[i]*2 + (dis[i]*2 - 1) // patience[i] * patience[i]) return best +1
3dff62
a80ddc
You are given a 2D integer array grid of size m x n, where each cell contains a positive integer. A cornered path is defined as a set of adjacent cells with at most one turn. More specifically, the path should exclusively move either horizontally or vertically up to the turn (if there is one), without returning to a previously visited cell. After the turn, the path will then move exclusively in the alternate direction: move vertically if it moved horizontally, and vice versa, also without returning to a previously visited cell. The product of a path is defined as the product of all the values in the path. Return the maximum number of trailing zeros in the product of a cornered path found in grid. Note: Horizontal movement means moving in either the left or right direction. Vertical movement means moving in either the up or down direction.   Example 1: Input: grid = [[23,17,15,3,20],[8,1,20,27,11],[9,4,6,2,21],[40,9,1,10,6],[22,7,4,5,3]] Output: 3 Explanation: The grid on the left shows a valid cornered path. It has a product of 15 * 20 * 6 * 1 * 10 = 18000 which has 3 trailing zeros. It can be shown that this is the maximum trailing zeros in the product of a cornered path. The grid in the middle is not a cornered path as it has more than one turn. The grid on the right is not a cornered path as it requires a return to a previously visited cell. Example 2: Input: grid = [[4,3,2],[7,6,1],[8,8,8]] Output: 0 Explanation: The grid is shown in the figure above. There are no cornered paths in the grid that result in a product with a trailing zero.   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 100000 1 <= m * n <= 100000 1 <= grid[i][j] <= 1000
class Solution(object): def maxTrailingZeros(self, grid): """ :type grid: List[List[int]] :rtype: int """ t, u, d, r = [[[0, 0] for _ in grid[0]] for _ in grid], [[[0, 0] for _ in grid[0]] for _ in grid], [[[0, 0] for _ in grid[0]] for _ in grid], 0 for i in range(len(grid)): for j in range(len(grid[0])): while not grid[i][j] % 2: grid[i][j], t[i][j][0] = grid[i][j] / 2, t[i][j][0] + 1 while not grid[i][j] % 5: grid[i][j], t[i][j][1] = grid[i][j] / 5, t[i][j][1] + 1 for j in range(len(grid[0])): v, f, w, g = 0, 0, 0, 0 for i in range(0, len(grid)): v, f, d[i][j][0], d[i][j][1], r = v + t[i][j][0], f + t[i][j][1], v + t[i][j][0], f + t[i][j][1], max(r, min(v + t[i][j][0], f + t[i][j][1])) for i in range(len(grid) - 1, -1, -1): w, g, u[i][j][0], u[i][j][1], r = w + t[i][j][0], g + t[i][j][1], w + t[i][j][0], g + t[i][j][1], max(r, min(w + t[i][j][0], g + t[i][j][1])) for i in range(len(grid)): v, f, w, g = 0, 0, 0, 0 for j in range(len(grid[0]) - 1): v, f, r = v + t[i][j][0], f + t[i][j][1], max(r, min(v + t[i][j][0] + u[i][j + 1][0], f + t[i][j][1] + u[i][j + 1][1]), min(v + t[i][j][0] + d[i][j + 1][0], f + t[i][j][1] + d[i][j + 1][1])) for j in range(len(grid[0]) - 1, 0, -1): w, g, r = w + t[i][j][0], g + t[i][j][1], max(r, min(w + t[i][j][0] + u[i][j - 1][0], g + t[i][j][1] + u[i][j - 1][1]), min(w + t[i][j][0] + d[i][j - 1][0], g + t[i][j][1] + d[i][j - 1][1])) return r
ca0ea6
a80ddc
You are given a 2D integer array grid of size m x n, where each cell contains a positive integer. A cornered path is defined as a set of adjacent cells with at most one turn. More specifically, the path should exclusively move either horizontally or vertically up to the turn (if there is one), without returning to a previously visited cell. After the turn, the path will then move exclusively in the alternate direction: move vertically if it moved horizontally, and vice versa, also without returning to a previously visited cell. The product of a path is defined as the product of all the values in the path. Return the maximum number of trailing zeros in the product of a cornered path found in grid. Note: Horizontal movement means moving in either the left or right direction. Vertical movement means moving in either the up or down direction.   Example 1: Input: grid = [[23,17,15,3,20],[8,1,20,27,11],[9,4,6,2,21],[40,9,1,10,6],[22,7,4,5,3]] Output: 3 Explanation: The grid on the left shows a valid cornered path. It has a product of 15 * 20 * 6 * 1 * 10 = 18000 which has 3 trailing zeros. It can be shown that this is the maximum trailing zeros in the product of a cornered path. The grid in the middle is not a cornered path as it has more than one turn. The grid on the right is not a cornered path as it requires a return to a previously visited cell. Example 2: Input: grid = [[4,3,2],[7,6,1],[8,8,8]] Output: 0 Explanation: The grid is shown in the figure above. There are no cornered paths in the grid that result in a product with a trailing zero.   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 100000 1 <= m * n <= 100000 1 <= grid[i][j] <= 1000
class Solution: def maxTrailingZeros(self, grid: List[List[int]]) -> int: def get_25(v) : to_ret = [0, 0] while v % 2 == 0 : v = v // 2 to_ret[0] += 1 while v % 5 == 0 : v = v // 5 to_ret[1] += 1 return to_ret m, n = len(grid), len(grid[0]) pre_sum1 = [[[0, 0] for a in range(n+1)] for b in range(m+1)] # 向上 pre_sum2 = [[[0, 0] for a in range(n+1)] for b in range(m+1)] # 向左 for i in range(m) : for j in range(n) : gs = get_25(grid[i][j]) pre_sum1[i+1][j+1][0] = pre_sum1[i][j+1][0] + gs[0] pre_sum1[i+1][j+1][1] = pre_sum1[i][j+1][1] + gs[1] pre_sum2[i+1][j+1][0] = pre_sum2[i+1][j][0] + gs[0] pre_sum2[i+1][j+1][1] = pre_sum2[i+1][j][1] + gs[1] to_ret = 0 for i in range(m) : for j in range(n) : a, b = pre_sum1[i+1][j+1] r1 = min(a+pre_sum2[i+1][j][0], b+pre_sum2[i+1][j][1]) to_ret = max(to_ret, r1) r2 = min(a+pre_sum2[i+1][-1][0]-pre_sum2[i+1][j+1][0], b+pre_sum2[i+1][-1][1]-pre_sum2[i+1][j+1][1]) to_ret = max(to_ret, r2) a = pre_sum1[-1][j+1][0] - pre_sum1[i][j+1][0] b = pre_sum1[-1][j+1][1] - pre_sum1[i][j+1][1] r3 = min(a+pre_sum2[i+1][j][0], b+pre_sum2[i+1][j][1]) to_ret = max(to_ret, r3) r4 = min(a+pre_sum2[i+1][-1][0]-pre_sum2[i+1][j+1][0], b+pre_sum2[i+1][-1][1]-pre_sum2[i+1][j+1][1]) to_ret = max(to_ret, r4) return to_ret
293969
8c5d7e
An underground railway system is keeping track of customer travel times between different stations. They are using this data to calculate the average time it takes to travel from one station to another. Implement the UndergroundSystem class: void checkIn(int id, string stationName, int t) A customer with a card ID equal to id, checks in at the station stationName at time t. A customer can only be checked into one place at a time. void checkOut(int id, string stationName, int t) A customer with a card ID equal to id, checks out from the station stationName at time t. double getAverageTime(string startStation, string endStation) Returns the average time it takes to travel from startStation to endStation. The average time is computed from all the previous traveling times from startStation to endStation that happened directly, meaning a check in at startStation followed by a check out from endStation. The time it takes to travel from startStation to endStation may be different from the time it takes to travel from endStation to startStation. There will be at least one customer that has traveled from startStation to endStation before getAverageTime is called. You may assume all calls to the checkIn and checkOut methods are consistent. If a customer checks in at time t1 then checks out at time t2, then t1 < t2. All events happen in chronological order.   Example 1: Input ["UndergroundSystem","checkIn","checkIn","checkIn","checkOut","checkOut","checkOut","getAverageTime","getAverageTime","checkIn","getAverageTime","checkOut","getAverageTime"] [[],[45,"Leyton",3],[32,"Paradise",8],[27,"Leyton",10],[45,"Waterloo",15],[27,"Waterloo",20],[32,"Cambridge",22],["Paradise","Cambridge"],["Leyton","Waterloo"],[10,"Leyton",24],["Leyton","Waterloo"],[10,"Waterloo",38],["Leyton","Waterloo"]] Output [null,null,null,null,null,null,null,14.00000,11.00000,null,11.00000,null,12.00000] Explanation UndergroundSystem undergroundSystem = new UndergroundSystem(); undergroundSystem.checkIn(45, "Leyton", 3); undergroundSystem.checkIn(32, "Paradise", 8); undergroundSystem.checkIn(27, "Leyton", 10); undergroundSystem.checkOut(45, "Waterloo", 15); // Customer 45 "Leyton" -> "Waterloo" in 15-3 = 12 undergroundSystem.checkOut(27, "Waterloo", 20); // Customer 27 "Leyton" -> "Waterloo" in 20-10 = 10 undergroundSystem.checkOut(32, "Cambridge", 22); // Customer 32 "Paradise" -> "Cambridge" in 22-8 = 14 undergroundSystem.getAverageTime("Paradise", "Cambridge"); // return 14.00000. One trip "Paradise" -> "Cambridge", (14) / 1 = 14 undergroundSystem.getAverageTime("Leyton", "Waterloo"); // return 11.00000. Two trips "Leyton" -> "Waterloo", (10 + 12) / 2 = 11 undergroundSystem.checkIn(10, "Leyton", 24); undergroundSystem.getAverageTime("Leyton", "Waterloo"); // return 11.00000 undergroundSystem.checkOut(10, "Waterloo", 38); // Customer 10 "Leyton" -> "Waterloo" in 38-24 = 14 undergroundSystem.getAverageTime("Leyton", "Waterloo"); // return 12.00000. Three trips "Leyton" -> "Waterloo", (10 + 12 + 14) / 3 = 12 Example 2: Input ["UndergroundSystem","checkIn","checkOut","getAverageTime","checkIn","checkOut","getAverageTime","checkIn","checkOut","getAverageTime"] [[],[10,"Leyton",3],[10,"Paradise",8],["Leyton","Paradise"],[5,"Leyton",10],[5,"Paradise",16],["Leyton","Paradise"],[2,"Leyton",21],[2,"Paradise",30],["Leyton","Paradise"]] Output [null,null,null,5.00000,null,null,5.50000,null,null,6.66667] Explanation UndergroundSystem undergroundSystem = new UndergroundSystem(); undergroundSystem.checkIn(10, "Leyton", 3); undergroundSystem.checkOut(10, "Paradise", 8); // Customer 10 "Leyton" -> "Paradise" in 8-3 = 5 undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 5.00000, (5) / 1 = 5 undergroundSystem.checkIn(5, "Leyton", 10); undergroundSystem.checkOut(5, "Paradise", 16); // Customer 5 "Leyton" -> "Paradise" in 16-10 = 6 undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 5.50000, (5 + 6) / 2 = 5.5 undergroundSystem.checkIn(2, "Leyton", 21); undergroundSystem.checkOut(2, "Paradise", 30); // Customer 2 "Leyton" -> "Paradise" in 30-21 = 9 undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 6.66667, (5 + 6 + 9) / 3 = 6.66667   Constraints: 1 <= id, t <= 1000000 1 <= stationName.length, startStation.length, endStation.length <= 10 All strings consist of uppercase and lowercase English letters and digits. There will be at most 2 * 10000 calls in total to checkIn, checkOut, and getAverageTime. Answers within 10-5 of the actual value will be accepted.
from collections import defaultdict class UndergroundSystem(object): def __init__(self): self.loc = {} self.t = {} self.s = defaultdict(float) self.c = defaultdict(float) def checkIn(self, id, stationName, t): """ :type id: int :type stationName: str :type t: int :rtype: None """ self.loc[id] = stationName self.t[id] = t def checkOut(self, id, stationName, t): """ :type id: int :type stationName: str :type t: int :rtype: None """ k = (self.loc[id], stationName) dur = t - self.t[id] del self.loc[id] del self.t[id] self.s[k] += dur self.c[k] += 1 def getAverageTime(self, startStation, endStation): """ :type startStation: str :type endStation: str :rtype: float """ k = (startStation, endStation) return self.s[k]/self.c[k] # Your UndergroundSystem object will be instantiated and called as such: # obj = UndergroundSystem() # obj.checkIn(id,stationName,t) # obj.checkOut(id,stationName,t) # param_3 = obj.getAverageTime(startStation,endStation)
9038d1
8c5d7e
An underground railway system is keeping track of customer travel times between different stations. They are using this data to calculate the average time it takes to travel from one station to another. Implement the UndergroundSystem class: void checkIn(int id, string stationName, int t) A customer with a card ID equal to id, checks in at the station stationName at time t. A customer can only be checked into one place at a time. void checkOut(int id, string stationName, int t) A customer with a card ID equal to id, checks out from the station stationName at time t. double getAverageTime(string startStation, string endStation) Returns the average time it takes to travel from startStation to endStation. The average time is computed from all the previous traveling times from startStation to endStation that happened directly, meaning a check in at startStation followed by a check out from endStation. The time it takes to travel from startStation to endStation may be different from the time it takes to travel from endStation to startStation. There will be at least one customer that has traveled from startStation to endStation before getAverageTime is called. You may assume all calls to the checkIn and checkOut methods are consistent. If a customer checks in at time t1 then checks out at time t2, then t1 < t2. All events happen in chronological order.   Example 1: Input ["UndergroundSystem","checkIn","checkIn","checkIn","checkOut","checkOut","checkOut","getAverageTime","getAverageTime","checkIn","getAverageTime","checkOut","getAverageTime"] [[],[45,"Leyton",3],[32,"Paradise",8],[27,"Leyton",10],[45,"Waterloo",15],[27,"Waterloo",20],[32,"Cambridge",22],["Paradise","Cambridge"],["Leyton","Waterloo"],[10,"Leyton",24],["Leyton","Waterloo"],[10,"Waterloo",38],["Leyton","Waterloo"]] Output [null,null,null,null,null,null,null,14.00000,11.00000,null,11.00000,null,12.00000] Explanation UndergroundSystem undergroundSystem = new UndergroundSystem(); undergroundSystem.checkIn(45, "Leyton", 3); undergroundSystem.checkIn(32, "Paradise", 8); undergroundSystem.checkIn(27, "Leyton", 10); undergroundSystem.checkOut(45, "Waterloo", 15); // Customer 45 "Leyton" -> "Waterloo" in 15-3 = 12 undergroundSystem.checkOut(27, "Waterloo", 20); // Customer 27 "Leyton" -> "Waterloo" in 20-10 = 10 undergroundSystem.checkOut(32, "Cambridge", 22); // Customer 32 "Paradise" -> "Cambridge" in 22-8 = 14 undergroundSystem.getAverageTime("Paradise", "Cambridge"); // return 14.00000. One trip "Paradise" -> "Cambridge", (14) / 1 = 14 undergroundSystem.getAverageTime("Leyton", "Waterloo"); // return 11.00000. Two trips "Leyton" -> "Waterloo", (10 + 12) / 2 = 11 undergroundSystem.checkIn(10, "Leyton", 24); undergroundSystem.getAverageTime("Leyton", "Waterloo"); // return 11.00000 undergroundSystem.checkOut(10, "Waterloo", 38); // Customer 10 "Leyton" -> "Waterloo" in 38-24 = 14 undergroundSystem.getAverageTime("Leyton", "Waterloo"); // return 12.00000. Three trips "Leyton" -> "Waterloo", (10 + 12 + 14) / 3 = 12 Example 2: Input ["UndergroundSystem","checkIn","checkOut","getAverageTime","checkIn","checkOut","getAverageTime","checkIn","checkOut","getAverageTime"] [[],[10,"Leyton",3],[10,"Paradise",8],["Leyton","Paradise"],[5,"Leyton",10],[5,"Paradise",16],["Leyton","Paradise"],[2,"Leyton",21],[2,"Paradise",30],["Leyton","Paradise"]] Output [null,null,null,5.00000,null,null,5.50000,null,null,6.66667] Explanation UndergroundSystem undergroundSystem = new UndergroundSystem(); undergroundSystem.checkIn(10, "Leyton", 3); undergroundSystem.checkOut(10, "Paradise", 8); // Customer 10 "Leyton" -> "Paradise" in 8-3 = 5 undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 5.00000, (5) / 1 = 5 undergroundSystem.checkIn(5, "Leyton", 10); undergroundSystem.checkOut(5, "Paradise", 16); // Customer 5 "Leyton" -> "Paradise" in 16-10 = 6 undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 5.50000, (5 + 6) / 2 = 5.5 undergroundSystem.checkIn(2, "Leyton", 21); undergroundSystem.checkOut(2, "Paradise", 30); // Customer 2 "Leyton" -> "Paradise" in 30-21 = 9 undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 6.66667, (5 + 6 + 9) / 3 = 6.66667   Constraints: 1 <= id, t <= 1000000 1 <= stationName.length, startStation.length, endStation.length <= 10 All strings consist of uppercase and lowercase English letters and digits. There will be at most 2 * 10000 calls in total to checkIn, checkOut, and getAverageTime. Answers within 10-5 of the actual value will be accepted.
class UndergroundSystem: def __init__(self): self.timecnts = dict() self.passengers = dict() def checkIn(self, id: int, stationName: str, t: int) -> None: self.passengers[id] = (stationName, t) def checkOut(self, id: int, stationName: str, t: int) -> None: start, t0 = self.passengers[id] trip = '{}->{}'.format(start, stationName) tspend = t - t0 if trip not in self.timecnts: self.timecnts[trip] = (tspend, 1) else: tott, totc = self.timecnts[trip] self.timecnts[trip] = (tott + tspend, totc + 1) def getAverageTime(self, startStation: str, endStation: str) -> float: trip = '{}->{}'.format(startStation, endStation) tott, totc = self.timecnts[trip] return float(tott) / totc # Your UndergroundSystem object will be instantiated and called as such: # obj = UndergroundSystem() # obj.checkIn(id,stationName,t) # obj.checkOut(id,stationName,t) # param_3 = obj.getAverageTime(startStation,endStation)
db70c9
fb2105
On an n x n chessboard, a knight starts at the cell (row, column) and attempts to make exactly k moves. The rows and columns are 0-indexed, so the top-left cell is (0, 0), and the bottom-right cell is (n - 1, n - 1). A chess knight has eight possible moves it can make, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction. Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there. The knight continues moving until it has made exactly k moves or has moved off the chessboard. Return the probability that the knight remains on the board after it has stopped moving.   Example 1: Input: n = 3, k = 2, row = 0, column = 0 Output: 0.06250 Explanation: There are two moves (to (1,2), (2,1)) that will keep the knight on the board. From each of those positions, there are also two moves that will keep the knight on the board. The total probability the knight stays on the board is 0.0625. Example 2: Input: n = 1, k = 0, row = 0, column = 0 Output: 1.00000   Constraints: 1 <= n <= 25 0 <= k <= 100 0 <= row, column <= n - 1
class Solution(object): def knightProbability(self, N, K, r, c): """ :type N: int :type K: int :type r: int :type c: int :rtype: float """ # 0-th stage, probability of staying on the board for K == 0 board = [[1]*N for _ in xrange(N)] moves = [(1,2), (2,1), (-1, 2), (-2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1)] for k in xrange(K): nextboard = [[0]*N for _ in xrange(N)] for x in xrange(N): for y in xrange(N): total = 8 alive = 8 for (dx, dy) in moves: newX = x + dx newY = y + dy if newX < 0 or newY < 0 or newX >= N or newY >= N: alive -= 1 else: alive -= 1-board[newX][newY] nextboard[x][y] = alive/8. board = nextboard return board[r][c]
e002cc
fb2105
On an n x n chessboard, a knight starts at the cell (row, column) and attempts to make exactly k moves. The rows and columns are 0-indexed, so the top-left cell is (0, 0), and the bottom-right cell is (n - 1, n - 1). A chess knight has eight possible moves it can make, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction. Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there. The knight continues moving until it has made exactly k moves or has moved off the chessboard. Return the probability that the knight remains on the board after it has stopped moving.   Example 1: Input: n = 3, k = 2, row = 0, column = 0 Output: 0.06250 Explanation: There are two moves (to (1,2), (2,1)) that will keep the knight on the board. From each of those positions, there are also two moves that will keep the knight on the board. The total probability the knight stays on the board is 0.0625. Example 2: Input: n = 1, k = 0, row = 0, column = 0 Output: 1.00000   Constraints: 1 <= n <= 25 0 <= k <= 100 0 <= row, column <= n - 1
class Solution: def knightProbability(self, N, K, r, c): """ :type N: int :type K: int :type r: int :type c: int :rtype: float """ dp = [[1 for i in range(N)] for j in range(N)] for rou in range(K): temp = [[0 for i in range(N)] for j in range(N)] for i in range(N): for j in range(N): for t in [(1, 2), (2, 1), (-1, -2), (-2, -1), (-1, 2), (1, -2), (2, -1), (-2, 1)]: if 0 <= i + t[0] < N and 0 <= j + t[1] < N: temp[i + t[0]][j + t[1]] += dp[i][j]/8 dp = temp return dp[r][c]
be8d8e
588b7f
Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).   Example 1: Input: nums = [2,2,1,1,5,3,3,5] Output: 7 Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4] = 5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice. Example 2: Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5] Output: 13   Constraints: 2 <= nums.length <= 100000 1 <= nums[i] <= 100000
class Solution(object): def maxEqualFreq(self, A): count = collections.Counter() freqs = collections.Counter() ans = 1 for i, x in enumerate(A): count[x] += 1 c = count[x] freqs[c] += 1 if c-1 > 0: freqs[c-1] -= 1 if freqs[c-1] == 0: del freqs[c-1] L = len(freqs) #print freqs if L <= 2: if L <= 1: k, = freqs.keys() fk = freqs[k] #print '.', i+1, ';', k, freqs[k] if k == 1 or fk == 1: ans = i + 1 else: a, b = freqs.keys() fa, fb = freqs[a], freqs[b] # remove a #print i+1,a,fa,';',b,fb if fa-1 == 0 and a-1 == b: ans = i + 1 if fb-1 == 0 and b-1 == a: ans = i + 1 if a == 1 and fa == 1 or b == 1 and fb == 1: ans = i + 1 return ans
4aea02
588b7f
Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).   Example 1: Input: nums = [2,2,1,1,5,3,3,5] Output: 7 Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4] = 5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice. Example 2: Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5] Output: 13   Constraints: 2 <= nums.length <= 100000 1 <= nums[i] <= 100000
class Solution: def maxEqualFreq(self, A): if len(A) <= 2: return len(A) count = {} uniqueCount = {} ans = 0 for i in range(len(A)): num = A[i] if num not in count: count[num] = 1 if 1 not in uniqueCount: uniqueCount[1] = 1 else: uniqueCount[1] += 1 else: count[num] += 1 prev = count[num] - 1 now = prev + 1 uniqueCount[prev] -= 1 if uniqueCount[prev] == 0: del uniqueCount[prev] if now not in uniqueCount: uniqueCount[now] = 1 else: uniqueCount[now] += 1 # if len(uniqueCount) <= 1: # ans = i + 1 # elif len(uniqueCount) == 2: if len(uniqueCount) == 1: for k, v in uniqueCount.items(): if k == 1 or v == 1: ans = i + 1 if len(uniqueCount) == 2: for k, v in uniqueCount.items(): if (k == 1 and v == 1) or (v == 1 and k-1 in uniqueCount): ans = i + 1 # print (i+1, num, count, uniqueCount) return ans
31e1c7
eabb46
You are given an m x n matrix of characters box representing a side-view of a box. Each cell of the box is one of the following: A stone '#' A stationary obstacle '*' Empty '.' The box is rotated 90 degrees clockwise, causing some of the stones to fall due to gravity. Each stone falls down until it lands on an obstacle, another stone, or the bottom of the box. Gravity does not affect the obstacles' positions, and the inertia from the box's rotation does not affect the stones' horizontal positions. It is guaranteed that each stone in box rests on an obstacle, another stone, or the bottom of the box. Return an n x m matrix representing the box after the rotation described above.   Example 1: Input: box = [["#",".","#"]] Output: [["."],   ["#"],   ["#"]] Example 2: Input: box = [["#",".","*","."],   ["#","#","*","."]] Output: [["#","."],   ["#","#"],   ["*","*"],   [".","."]] Example 3: Input: box = [["#","#","*",".","*","."],   ["#","#","#","*",".","."],   ["#","#","#",".","#","."]] Output: [[".","#","#"],   [".","#","#"],   ["#","#","*"],   ["#","*","."],   ["#",".","*"],   ["#",".","."]]   Constraints: m == box.length n == box[i].length 1 <= m, n <= 500 box[i][j] is either '#', '*', or '.'.
def f(row): n = len(row) for i in range(n - 1, -1, -1): if row[i] == '#': j = i + 1 while j < n and row[j] == '.': j += 1 # j == n or row[j] != '.' row[i] = '.' row[j - 1] = '#' return row class Solution: def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]: box = [f(row) for row in box] rows = box[::-1] return list(zip(*rows))
8ac372
eabb46
You are given an m x n matrix of characters box representing a side-view of a box. Each cell of the box is one of the following: A stone '#' A stationary obstacle '*' Empty '.' The box is rotated 90 degrees clockwise, causing some of the stones to fall due to gravity. Each stone falls down until it lands on an obstacle, another stone, or the bottom of the box. Gravity does not affect the obstacles' positions, and the inertia from the box's rotation does not affect the stones' horizontal positions. It is guaranteed that each stone in box rests on an obstacle, another stone, or the bottom of the box. Return an n x m matrix representing the box after the rotation described above.   Example 1: Input: box = [["#",".","#"]] Output: [["."],   ["#"],   ["#"]] Example 2: Input: box = [["#",".","*","."],   ["#","#","*","."]] Output: [["#","."],   ["#","#"],   ["*","*"],   [".","."]] Example 3: Input: box = [["#","#","*",".","*","."],   ["#","#","#","*",".","."],   ["#","#","#",".","#","."]] Output: [[".","#","#"],   [".","#","#"],   ["#","#","*"],   ["#","*","."],   ["#",".","*"],   ["#",".","."]]   Constraints: m == box.length n == box[i].length 1 <= m, n <= 500 box[i][j] is either '#', '*', or '.'.
class Solution(object): def rotateTheBox(self, b): b = map(list,zip(*b)) n = len(b) m = len(b[0]) for j in range(m): x = n - 1 for i in range(n)[::-1]: if b[i][j] == '*': x = i - 1 elif b[i][j] == '#': b[i][j] = '.' b[x][j] = '#' x = x - 1 for i in range(n): l, r = 0, m - 1 while l < r: b[i][l], b[i][r] = b[i][r], b[i][l] l += 1 r -= 1 return b
26519e
2ee41c
You are given a license key represented as a string s that consists of only alphanumeric characters and dashes. The string is separated into n + 1 groups by n dashes. You are also given an integer k. We want to reformat the string s such that each group contains exactly k characters, except for the first group, which could be shorter than k but still must contain at least one character. Furthermore, there must be a dash inserted between two groups, and you should convert all lowercase letters to uppercase. Return the reformatted license key.   Example 1: Input: s = "5F3Z-2e-9-w", k = 4 Output: "5F3Z-2E9W" Explanation: The string s has been split into two parts, each part has 4 characters. Note that the two extra dashes are not needed and can be removed. Example 2: Input: s = "2-5g-3-J", k = 2 Output: "2-5G-3J" Explanation: The string s has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above.   Constraints: 1 <= s.length <= 100000 s consists of English letters, digits, and dashes '-'. 1 <= k <= 10000
class Solution(object): def licenseKeyFormatting(self, S, K): """ :type S: str :type K: int :rtype: str """ org = '' for ch in S: if ch != '-': if 'a' <= ch <= 'z': org += ch.upper() else: org += ch res = '' tmp = len(org) % K or K res += org[:tmp] for i in range((len(org) - 1) / K): res += '-' + org[i * K + tmp: (i + 1) * K + tmp] return res
cc74f3
9c109e
There is a directed graph of n colored nodes and m edges. The nodes are numbered from 0 to n - 1. You are given a string colors where colors[i] is a lowercase English letter representing the color of the ith node in this graph (0-indexed). You are also given a 2D array edges where edges[j] = [aj, bj] indicates that there is a directed edge from node aj to node bj. A valid path in the graph is a sequence of nodes x1 -> x2 -> x3 -> ... -> xk such that there is a directed edge from xi to xi+1 for every 1 <= i < k. The color value of the path is the number of nodes that are colored the most frequently occurring color along that path. Return the largest color value of any valid path in the given graph, or -1 if the graph contains a cycle.   Example 1: Input: colors = "abaca", edges = [[0,1],[0,2],[2,3],[3,4]] Output: 3 Explanation: The path 0 -> 2 -> 3 -> 4 contains 3 nodes that are colored "a" (red in the above image). Example 2: Input: colors = "a", edges = [[0,0]] Output: -1 Explanation: There is a cycle from 0 to 0.   Constraints: n == colors.length m == edges.length 1 <= n <= 100000 0 <= m <= 100000 colors consists of lowercase English letters. 0 <= aj, bj < n
class Solution(object): def largestPathValue(self, colors, edges): """ :type colors: str :type edges: List[List[int]] :rtype: int """ c = [ord(ch) - ord('a') for ch in colors] n = len(c) edges = set((u,v) for u,v in edges) adj = [[] for _ in xrange(n)] adjt = [[] for _ in xrange(n)] deg = [0]*n for u, v in edges: adj[u].append(v) adjt[v].append(u) deg[u] += 1 q = [u for u in xrange(n) if deg[u] == 0] topo = [] while q: u = q.pop() topo.append(u) for v in adjt[u]: deg[v] -= 1 if deg[v] == 0: q.append(v) if len(topo) != n: return -1 # cycle r = 0 for color in set(c): f = [0]*n for u in topo: f[u] = 0 for v in adj[u]: f[u] = max(f[u], f[v]) if c[u] == color: f[u] += 1 r = max(r, f[u]) return r
53d07d
9c109e
There is a directed graph of n colored nodes and m edges. The nodes are numbered from 0 to n - 1. You are given a string colors where colors[i] is a lowercase English letter representing the color of the ith node in this graph (0-indexed). You are also given a 2D array edges where edges[j] = [aj, bj] indicates that there is a directed edge from node aj to node bj. A valid path in the graph is a sequence of nodes x1 -> x2 -> x3 -> ... -> xk such that there is a directed edge from xi to xi+1 for every 1 <= i < k. The color value of the path is the number of nodes that are colored the most frequently occurring color along that path. Return the largest color value of any valid path in the given graph, or -1 if the graph contains a cycle.   Example 1: Input: colors = "abaca", edges = [[0,1],[0,2],[2,3],[3,4]] Output: 3 Explanation: The path 0 -> 2 -> 3 -> 4 contains 3 nodes that are colored "a" (red in the above image). Example 2: Input: colors = "a", edges = [[0,0]] Output: -1 Explanation: There is a cycle from 0 to 0.   Constraints: n == colors.length m == edges.length 1 <= n <= 100000 0 <= m <= 100000 colors consists of lowercase English letters. 0 <= aj, bj < n
import functools class Solution: def largestPathValue(self, c: str, edges: List[List[int]]) -> int: n = len(c) g = [[] for vertex in range(n)] for source, destination in edges: g[source].append(destination) u = [0] * n def dfs0(v): u[v] = 1 r = True for w in g[v]: if u[w] == 1: r = False elif not u[w]: if not dfs0(w): r = False u[v] = 2 return r for v in range(n): if not dfs0(v): return -1 @functools.cache def dfs(v): a = [0] * 26 for w in g[v]: for i, k in enumerate(dfs(w)): a[i] = max(a[i], k) a[ord(c[v]) - ord('a')] += 1 return a m = 0 for v in range(n): m = max(m, max(dfs(v))) return m
fb26cd
ddcc53
Given an integer array nums, return the maximum possible sum of elements of the array such that it is divisible by three.   Example 1: Input: nums = [3,6,5,1,8] Output: 18 Explanation: Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3). Example 2: Input: nums = [4] Output: 0 Explanation: Since 4 is not divisible by 3, do not pick any number. Example 3: Input: nums = [1,2,3,4,4] Output: 12 Explanation: Pick numbers 1, 3, 4 and 4 their sum is 12 (maximum sum divisible by 3).   Constraints: 1 <= nums.length <= 4 * 10000 1 <= nums[i] <= 10000
class Solution(object): def maxSumDivThree(self, A): ans = base = 0 r1 = [] r2 = [] for x in A: r = x % 3 if r == 0: base += x elif r == 1: r1.append(x) else: r2.append(x) r1.sort(reverse=True) r2.sort(reverse=True) Sr1 = sum(r1) Sr2 = sum(r2) Nr1 = len(r1) Nr2 = len(r2) Pr1 = [0] Pr2 = [0] for x in r1: Pr1.append(Pr1[-1] + x) for x in r2: Pr2.append(Pr2[-1] + x) for take in xrange(min(len(r1), len(r2)) + 1): rem1 = Nr1 - take rem1 //= 3 rem1 *= 3 rem2 = Nr2 - take rem2 //= 3 rem2 *= 3 #print ';', Pr1, Pr2, ';',rem1, rem2, take cand = Pr1[take + rem1 ] + Pr2[take + rem2 ] + base if cand > ans: ans = cand return ans """ P = [0] for x in A: P.append(P[-1] + x) mins = [0, None, None] ans = 0 for j in xrange(1, len(P)): p = P[j] r = p % 3 if mins[r] is not None: cand = p - mins[r] if cand > ans: ans = cand if mins[r] is None: mins[r] = p else: mins[r] = min(mins[r], p) return ans """
3821c5
ddcc53
Given an integer array nums, return the maximum possible sum of elements of the array such that it is divisible by three.   Example 1: Input: nums = [3,6,5,1,8] Output: 18 Explanation: Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3). Example 2: Input: nums = [4] Output: 0 Explanation: Since 4 is not divisible by 3, do not pick any number. Example 3: Input: nums = [1,2,3,4,4] Output: 12 Explanation: Pick numbers 1, 3, 4 and 4 their sum is 12 (maximum sum divisible by 3).   Constraints: 1 <= nums.length <= 4 * 10000 1 <= nums[i] <= 10000
class Solution: def maxSumDivThree(self, nums: List[int]) -> int: n1, n2 = [], [] ans = 0 for num in nums: if num % 3 == 0: ans += num elif num % 3 == 1: n1.append(num) ans += num else: n2.append(num) ans += num n1.sort(reverse=True) n2.sort(reverse=True) if len(n1) % 3 == len(n2) % 3: return ans if len(n1) % 3 > len(n2) % 3: n1, n2 = n2, n1 if len(n1) % 3 == 0 and len(n2) % 3 == 1: if not n1: return ans - n2[-1] return ans - min(n2[-1], n1[-1] + n1[-2]) if len(n1) % 3 == 0 and len(n2) % 3 == 2: if not n1: return ans - n2[-1] - n2[-2] return ans - min(n1[-1], n2[-1] + n2[-2]) if len(n1) % 3 == 1 and len(n2) % 3 == 2: if len(n1) == 1: return ans - n2[-1] return ans - min(n2[-1], n1[-1] + n1[-2])
f14b3f
765038
A die simulator generates a random number from 1 to 6 for each roll. You introduced a constraint to the generator such that it cannot roll the number i more than rollMax[i] (1-indexed) consecutive times. Given an array of integers rollMax and an integer n, return the number of distinct sequences that can be obtained with exact n rolls. Since the answer may be too large, return it modulo 10^9 + 7. Two sequences are considered different if at least one element differs from each other.   Example 1: Input: n = 2, rollMax = [1,1,2,2,2,3] Output: 34 Explanation: There will be 2 rolls of die, if there are no constraints on the die, there are 6 * 6 = 36 possible combinations. In this case, looking at rollMax array, the numbers 1 and 2 appear at most once consecutively, therefore sequences (1,1) and (2,2) cannot occur, so the final answer is 36-2 = 34. Example 2: Input: n = 2, rollMax = [1,1,1,1,1,1] Output: 30 Example 3: Input: n = 3, rollMax = [1,1,1,2,2,3] Output: 181   Constraints: 1 <= n <= 5000 rollMax.length == 6 1 <= rollMax[i] <= 15
from functools import lru_cache class Solution: def dieSimulator(self, n, rollMax): MOD = 10 ** 9 + 7 @lru_cache(None) def dp(i, j, k): # i rolls, recently rolled j, k times if i == 0: return 1 ans = 0 for d in range(6): if d != j: ans += dp(i-1, d, 1) elif k + 1 <= rollMax[d]: ans += dp(i-1, d, k+1) ans %= MOD return ans return dp(n, -1, 0) % MOD
281a35
765038
A die simulator generates a random number from 1 to 6 for each roll. You introduced a constraint to the generator such that it cannot roll the number i more than rollMax[i] (1-indexed) consecutive times. Given an array of integers rollMax and an integer n, return the number of distinct sequences that can be obtained with exact n rolls. Since the answer may be too large, return it modulo 10^9 + 7. Two sequences are considered different if at least one element differs from each other.   Example 1: Input: n = 2, rollMax = [1,1,2,2,2,3] Output: 34 Explanation: There will be 2 rolls of die, if there are no constraints on the die, there are 6 * 6 = 36 possible combinations. In this case, looking at rollMax array, the numbers 1 and 2 appear at most once consecutively, therefore sequences (1,1) and (2,2) cannot occur, so the final answer is 36-2 = 34. Example 2: Input: n = 2, rollMax = [1,1,1,1,1,1] Output: 30 Example 3: Input: n = 3, rollMax = [1,1,1,2,2,3] Output: 181   Constraints: 1 <= n <= 5000 rollMax.length == 6 1 <= rollMax[i] <= 15
class Solution(object): def dieSimulator(self, n, rollMax): M = 10**9+7 data = [[1]+[0]*(rollMax[i]-1) for i in range(6)] for _ in range(n-1): sums = [sum(x) for x in data] s = sum(sums) for j in range(6): n = rollMax[j] for k in range(n-1,0,-1): data[j][k] = data[j][k-1] data[j][0] = (s - sums[j]) % M #print (data) return sum([sum(x) for x in data]) % M
c1b4a4
241385
Given an n x n binary matrix grid, return the length of the shortest clear path in the matrix. If there is no clear path, return -1. A clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0)) to the bottom-right cell (i.e., (n - 1, n - 1)) such that: All the visited cells of the path are 0. All the adjacent cells of the path are 8-directionally connected (i.e., they are different and they share an edge or a corner). The length of a clear path is the number of visited cells of this path.   Example 1: Input: grid = [[0,1],[1,0]] Output: 2 Example 2: Input: grid = [[0,0,0],[1,1,0],[1,1,0]] Output: 4 Example 3: Input: grid = [[1,0,0],[1,1,0],[1,1,0]] Output: -1   Constraints: n == grid.length n == grid[i].length 1 <= n <= 100 grid[i][j] is 0 or 1
class Solution: def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int: if grid[0][0] == 1: return -1 def neighbor8(i, j): n = len(grid) for di in (-1, 0, 1): for dj in (-1, 0, 1): if di == dj == 0: continue newi, newj = i + di, j + dj if 0 <= newi < n and 0 <= newj < n and grid[newi][newj] == 0: yield (newi, newj) n = len(grid) ds = [[math.inf] * n for _ in range(n)] queue = collections.deque([(0, 0)]) ds[0][0] = 1 while queue: i, j = queue.popleft() if i == j == n - 1: return ds[n - 1][n - 1] for newi, newj in neighbor8(i, j): if ds[i][j] + 1 < ds[newi][newj]: ds[newi][newj] = ds[i][j] + 1 queue.append((newi, newj)) return -1
d71672
241385
Given an n x n binary matrix grid, return the length of the shortest clear path in the matrix. If there is no clear path, return -1. A clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0)) to the bottom-right cell (i.e., (n - 1, n - 1)) such that: All the visited cells of the path are 0. All the adjacent cells of the path are 8-directionally connected (i.e., they are different and they share an edge or a corner). The length of a clear path is the number of visited cells of this path.   Example 1: Input: grid = [[0,1],[1,0]] Output: 2 Example 2: Input: grid = [[0,0,0],[1,1,0],[1,1,0]] Output: 4 Example 3: Input: grid = [[1,0,0],[1,1,0],[1,1,0]] Output: -1   Constraints: n == grid.length n == grid[i].length 1 <= n <= 100 grid[i][j] is 0 or 1
from collections import deque class Solution(object): def shortestPathBinaryMatrix(self, grid): """ :type grid: List[List[int]] :rtype: int """ n, m = len(grid), len(grid[0]) if grid[0][0] or grid[n-1][m-1]: return -1 q = deque() q.append((0,0,1)) seen = set() while q: i, j, d = q.popleft() if (i, j) in seen: continue if i==n-1 and j==m-1: return d seen.add((i, j)) for di in xrange(-1, 2): ni = i + di if ni < 0 or ni >= n: continue for dj in xrange(-1, 2): nj = j + dj if nj < 0 or nj >= m: continue if grid[ni][nj] or (ni, nj) in seen: continue q.append((ni, nj, d+1)) return -1
b45d8a
4191a1
You are given an array of strings ideas that represents a list of names to be used in the process of naming a company. The process of naming a company is as follows: Choose 2 distinct names from ideas, call them ideaA and ideaB. Swap the first letters of ideaA and ideaB with each other. If both of the new names are not found in the original ideas, then the name ideaA ideaB (the concatenation of ideaA and ideaB, separated by a space) is a valid company name. Otherwise, it is not a valid name. Return the number of distinct valid names for the company.   Example 1: Input: ideas = ["coffee","donuts","time","toffee"] Output: 6 Explanation: The following selections are valid: - ("coffee", "donuts"): The company name created is "doffee conuts". - ("donuts", "coffee"): The company name created is "conuts doffee". - ("donuts", "time"): The company name created is "tonuts dime". - ("donuts", "toffee"): The company name created is "tonuts doffee". - ("time", "donuts"): The company name created is "dime tonuts". - ("toffee", "donuts"): The company name created is "doffee tonuts". Therefore, there are a total of 6 distinct company names. The following are some examples of invalid selections: - ("coffee", "time"): The name "toffee" formed after swapping already exists in the original array. - ("time", "toffee"): Both names are still the same after swapping and exist in the original array. - ("coffee", "toffee"): Both names formed after swapping already exist in the original array. Example 2: Input: ideas = ["lack","back"] Output: 0 Explanation: There are no valid selections. Therefore, 0 is returned.   Constraints: 2 <= ideas.length <= 5 * 10000 1 <= ideas[i].length <= 10 ideas[i] consists of lowercase English letters. All the strings in ideas are unique.
from collections import defaultdict from itertools import combinations class Solution(object): def distinctNames(self, ideas): """ :type ideas: List[str] :rtype: int """ d = defaultdict(set) for w in ideas: d[w[0]].add(w[1:]) r = 0 for a, b in combinations(d, 2): d1 = d[a] d2 = d[b] if len(d1) > len(d2): d1, d2 = d2, d1 overlap = sum(1 for w in d1 if w in d2) r += (len(d1) - overlap) * (len(d2) - overlap) return 2 * r
a3e6e7
4191a1
You are given an array of strings ideas that represents a list of names to be used in the process of naming a company. The process of naming a company is as follows: Choose 2 distinct names from ideas, call them ideaA and ideaB. Swap the first letters of ideaA and ideaB with each other. If both of the new names are not found in the original ideas, then the name ideaA ideaB (the concatenation of ideaA and ideaB, separated by a space) is a valid company name. Otherwise, it is not a valid name. Return the number of distinct valid names for the company.   Example 1: Input: ideas = ["coffee","donuts","time","toffee"] Output: 6 Explanation: The following selections are valid: - ("coffee", "donuts"): The company name created is "doffee conuts". - ("donuts", "coffee"): The company name created is "conuts doffee". - ("donuts", "time"): The company name created is "tonuts dime". - ("donuts", "toffee"): The company name created is "tonuts doffee". - ("time", "donuts"): The company name created is "dime tonuts". - ("toffee", "donuts"): The company name created is "doffee tonuts". Therefore, there are a total of 6 distinct company names. The following are some examples of invalid selections: - ("coffee", "time"): The name "toffee" formed after swapping already exists in the original array. - ("time", "toffee"): Both names are still the same after swapping and exist in the original array. - ("coffee", "toffee"): Both names formed after swapping already exist in the original array. Example 2: Input: ideas = ["lack","back"] Output: 0 Explanation: There are no valid selections. Therefore, 0 is returned.   Constraints: 2 <= ideas.length <= 5 * 10000 1 <= ideas[i].length <= 10 ideas[i] consists of lowercase English letters. All the strings in ideas are unique.
class Solution: def distinctNames(self, ideas: List[str]) -> int: dictt = collections.defaultdict(set) for t in ideas : dictt[t[1:]].add(t[0]) cs = 'abcdefghijklmnopqrstuvwxyz' cts = {a:{b:0 for b in cs} for a in cs} #cts[a][b] 表示,之前以a为开头,且可以和b开头的互换的,有多少个。 to_ret = 0 for ktail in dictt : vhead = dictt[ktail] for ht in vhead : for a in cts : if a in vhead : continue to_ret += cts[a][ht] for ht in vhead : for a in cs : if a in vhead : continue cts[ht][a] += 1 return to_ret * 2
459bb6
67f866
A game is played by a cat and a mouse named Cat and Mouse. The environment is represented by a grid of size rows x cols, where each element is a wall, floor, player (Cat, Mouse), or food. Players are represented by the characters 'C'(Cat),'M'(Mouse). Floors are represented by the character '.' and can be walked on. Walls are represented by the character '#' and cannot be walked on. Food is represented by the character 'F' and can be walked on. There is only one of each character 'C', 'M', and 'F' in grid. Mouse and Cat play according to the following rules: Mouse moves first, then they take turns to move. During each turn, Cat and Mouse can jump in one of the four directions (left, right, up, down). They cannot jump over the wall nor outside of the grid. catJump, mouseJump are the maximum lengths Cat and Mouse can jump at a time, respectively. Cat and Mouse can jump less than the maximum length. Staying in the same position is allowed. Mouse can jump over Cat. The game can end in 4 ways: If Cat occupies the same position as Mouse, Cat wins. If Cat reaches the food first, Cat wins. If Mouse reaches the food first, Mouse wins. If Mouse cannot get to the food within 1000 turns, Cat wins. Given a rows x cols matrix grid and two integers catJump and mouseJump, return true if Mouse can win the game if both Cat and Mouse play optimally, otherwise return false.   Example 1: Input: grid = ["####F","#C...","M...."], catJump = 1, mouseJump = 2 Output: true Explanation: Cat cannot catch Mouse on its turn nor can it get the food before Mouse. Example 2: Input: grid = ["M.C...F"], catJump = 1, mouseJump = 4 Output: true Example 3: Input: grid = ["M.C...F"], catJump = 1, mouseJump = 3 Output: false   Constraints: rows == grid.length cols = grid[i].length 1 <= rows, cols <= 8 grid[i][j] consist only of characters 'C', 'M', 'F', '.', and '#'. There is only one of each character 'C', 'M', and 'F' in grid. 1 <= catJump, mouseJump <= 8
class Solution(object): def canMouseWin(self, grid, catJump, mouseJump): """ :type grid: List[str] :type catJump: int :type mouseJump: int :rtype: bool """ # if there is winning solution, it's length is probably very short (<100) a = grid n, m = len(a), len(a[0]) mpos = cpos = fpos = -1 for i in xrange(n): for j in xrange(m): if a[i][j] == 'M': mpos = i*m + j elif a[i][j] == 'C': cpos = i*m + j elif a[i][j] == 'F': fpos = i*m + j def traj(i, j, d): if grid[i][j] == '#': return [] pos = i*m+j nei = [pos] for k in xrange(1, d+1): if i+k>=n or grid[i+k][j]=='#': break nei.append(pos+k*m) for k in xrange(1, d+1): if i-k<0 or grid[i-k][j]=='#': break nei.append(pos-k*m) for k in xrange(1, d+1): if j+k>=m or grid[i][j+k]=='#': break nei.append(pos+k) for k in xrange(1, d+1): if j-k<0 or grid[i][j-k]=='#': break nei.append(pos-k) return nei mnei = [traj(i, j, mouseJump) for i in xrange(n) for j in xrange(m)] cnei = [traj(i, j, catJump) for i in xrange(n) for j in xrange(m)] k = n * m lim = 100 cache = [[-1]*(k*k) for _ in xrange(lim)] def mouse_win(mpos, cpos, turn): if turn == lim: return 0 e = mpos*k+cpos if cache[turn][e] >= 0: return cache[turn][e] == 1 if cpos == fpos or cpos == mpos: return 0 if mpos == fpos: return 1 if turn & 1: # cat turn if all(mouse_win(mpos, newcpos, turn+1) for newcpos in cnei[cpos]): cache[turn][e] = 1 else: cache[turn][e] = 0 else: # mouse turn if any(mouse_win(newmpos, cpos, turn+1) for newmpos in mnei[mpos]): cache[turn][e] = 1 else: cache[turn][e] = 0 return cache[turn][e] == 1 return mouse_win(mpos, cpos, 0)
5f6346
67f866
A game is played by a cat and a mouse named Cat and Mouse. The environment is represented by a grid of size rows x cols, where each element is a wall, floor, player (Cat, Mouse), or food. Players are represented by the characters 'C'(Cat),'M'(Mouse). Floors are represented by the character '.' and can be walked on. Walls are represented by the character '#' and cannot be walked on. Food is represented by the character 'F' and can be walked on. There is only one of each character 'C', 'M', and 'F' in grid. Mouse and Cat play according to the following rules: Mouse moves first, then they take turns to move. During each turn, Cat and Mouse can jump in one of the four directions (left, right, up, down). They cannot jump over the wall nor outside of the grid. catJump, mouseJump are the maximum lengths Cat and Mouse can jump at a time, respectively. Cat and Mouse can jump less than the maximum length. Staying in the same position is allowed. Mouse can jump over Cat. The game can end in 4 ways: If Cat occupies the same position as Mouse, Cat wins. If Cat reaches the food first, Cat wins. If Mouse reaches the food first, Mouse wins. If Mouse cannot get to the food within 1000 turns, Cat wins. Given a rows x cols matrix grid and two integers catJump and mouseJump, return true if Mouse can win the game if both Cat and Mouse play optimally, otherwise return false.   Example 1: Input: grid = ["####F","#C...","M...."], catJump = 1, mouseJump = 2 Output: true Explanation: Cat cannot catch Mouse on its turn nor can it get the food before Mouse. Example 2: Input: grid = ["M.C...F"], catJump = 1, mouseJump = 4 Output: true Example 3: Input: grid = ["M.C...F"], catJump = 1, mouseJump = 3 Output: false   Constraints: rows == grid.length cols = grid[i].length 1 <= rows, cols <= 8 grid[i][j] consist only of characters 'C', 'M', 'F', '.', and '#'. There is only one of each character 'C', 'M', and 'F' in grid. 1 <= catJump, mouseJump <= 8
class Solution: def canMouseWin(self, grid: List[str], catJump: int, mouseJump: int) -> bool: row, column = len(grid), len(grid[0]) for i in range(row): for j in range(column): if grid[i][j] == "C": cx, cy = i, j elif grid[i][j] == "M": mx, my = i, j elif grid[i][j] == "F": fx, fy = i, j from functools import lru_cache @lru_cache(None) def dfs(cat, rat, move): # true if mouse wins else false if cat == rat or cat == (fx, fy) or move>=2*row*column: return False if rat == (fx, fy): return True if move & 1: # cat x, y = cat for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0)]: for j in range(catJump+1): xx, yy = x+dx*j, y+dy*j if xx<0 or xx >= row or yy<0 or yy>=column or grid[xx][yy]=="#": break if not dfs((xx, yy), rat, move+1): return False return True else: # mouse x, y = rat for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0)]: for j in range(mouseJump+1): xx, yy = x+dx*j, y+dy*j if xx<0 or xx >= row or yy<0 or yy>=column or grid[xx][yy]=="#": break if dfs(cat, (xx, yy), move+1): return True return False return dfs((cx, cy), (mx, my), 0)
5bae89
7e090d
You are given a tree (i.e. a connected, undirected graph that has no cycles) rooted at node 0 consisting of n nodes numbered from 0 to n - 1. The tree is represented by a 0-indexed array parent of size n, where parent[i] is the parent of node i. Since node 0 is the root, parent[0] == -1. You are also given a string s of length n, where s[i] is the character assigned to node i. Return the length of the longest path in the tree such that no pair of adjacent nodes on the path have the same character assigned to them.   Example 1: Input: parent = [-1,0,0,1,1,2], s = "abacbe" Output: 3 Explanation: The longest path where each two adjacent nodes have different characters in the tree is the path: 0 -> 1 -> 3. The length of this path is 3, so 3 is returned. It can be proven that there is no longer path that satisfies the conditions. Example 2: Input: parent = [-1,0,0,0], s = "aabc" Output: 3 Explanation: The longest path where each two adjacent nodes have different characters is the path: 2 -> 0 -> 3. The length of this path is 3, so 3 is returned.   Constraints: n == parent.length == s.length 1 <= n <= 100000 0 <= parent[i] <= n - 1 for all i >= 1 parent[0] == -1 parent represents a valid tree. s consists of only lowercase English letters.
class Solution(object): def longestPath(self, parent, s): """ :type parent: List[int] :type s: str :rtype: int """ g = [[] for _ in parent] for i in range(1, len(parent)): g[parent[i]].append(i) def h(n): r, m = [1, 1], [0, 0] for c in g[n]: l = h(c) r[0], r[1], m = max(r[0], l[0]), r[1] if s[c] == s[n] else max(r[1], 1 + l[1]), m if s[c] == s[n] else [l[1], m[0]] if l[1] > m[0] else [m[0], l[1]] if l[1] > m[1] else m return [max(r[0], 1 + m[0] + m[1]), r[1]] return h(0)[0]
e42876
7e090d
You are given a tree (i.e. a connected, undirected graph that has no cycles) rooted at node 0 consisting of n nodes numbered from 0 to n - 1. The tree is represented by a 0-indexed array parent of size n, where parent[i] is the parent of node i. Since node 0 is the root, parent[0] == -1. You are also given a string s of length n, where s[i] is the character assigned to node i. Return the length of the longest path in the tree such that no pair of adjacent nodes on the path have the same character assigned to them.   Example 1: Input: parent = [-1,0,0,1,1,2], s = "abacbe" Output: 3 Explanation: The longest path where each two adjacent nodes have different characters in the tree is the path: 0 -> 1 -> 3. The length of this path is 3, so 3 is returned. It can be proven that there is no longer path that satisfies the conditions. Example 2: Input: parent = [-1,0,0,0], s = "aabc" Output: 3 Explanation: The longest path where each two adjacent nodes have different characters is the path: 2 -> 0 -> 3. The length of this path is 3, so 3 is returned.   Constraints: n == parent.length == s.length 1 <= n <= 100000 0 <= parent[i] <= n - 1 for all i >= 1 parent[0] == -1 parent represents a valid tree. s consists of only lowercase English letters.
class Solution: def longestPath(self, parent: List[int], s: str) -> int: sons = collections.defaultdict(list) for i, t in enumerate(parent) : sons[t].append(i) self.to_ret = 0 def visit(node=0) : lcs = [] for st in sons[node] : lct = visit(st) if not s[st] == s[node] : lcs.append(lct) # print(node, lcs) if len(lcs) == 0 : ret = 1 self.to_ret = max(1, self.to_ret) else : lcs = sorted(lcs, reverse=True) ret = lcs[0] + 1 self.to_ret = max(1+sum(lcs[:2]), self.to_ret) return ret visit() return self.to_ret
f3a6c2
82ff43
Alice and Bob continue their games with stones. There is a row of n stones, and each stone has an associated value. You are given an integer array stones, where stones[i] is the value of the ith stone. Alice and Bob take turns, with Alice starting first. On each turn, the player may remove any stone from stones. The player who removes a stone loses if the sum of the values of all removed stones is divisible by 3. Bob will win automatically if there are no remaining stones (even if it is Alice's turn). Assuming both players play optimally, return true if Alice wins and false if Bob wins.   Example 1: Input: stones = [2,1] Output: true Explanation: The game will be played as follows: - Turn 1: Alice can remove either stone. - Turn 2: Bob removes the remaining stone. The sum of the removed stones is 1 + 2 = 3 and is divisible by 3. Therefore, Bob loses and Alice wins the game. Example 2: Input: stones = [2] Output: false Explanation: Alice will remove the only stone, and the sum of the values on the removed stones is 2. Since all the stones are removed and the sum of values is not divisible by 3, Bob wins the game. Example 3: Input: stones = [5,1,2,4,3] Output: false Explanation: Bob will always win. One possible way for Bob to win is shown below: - Turn 1: Alice can remove the second stone with value 1. Sum of removed stones = 1. - Turn 2: Bob removes the fifth stone with value 3. Sum of removed stones = 1 + 3 = 4. - Turn 3: Alices removes the fourth stone with value 4. Sum of removed stones = 1 + 3 + 4 = 8. - Turn 4: Bob removes the third stone with value 2. Sum of removed stones = 1 + 3 + 4 + 2 = 10. - Turn 5: Alice removes the first stone with value 5. Sum of removed stones = 1 + 3 + 4 + 2 + 5 = 15. Alice loses the game because the sum of the removed stones (15) is divisible by 3. Bob wins the game.   Constraints: 1 <= stones.length <= 100000 1 <= stones[i] <= 10000
from typing import List class Solution: def stoneGameIX(self, stones: List[int]) -> bool: cnt = [0, 0, 0] for stone in stones: cnt[stone % 3] += 1 if cnt[1] > 0: if cnt[1] >= cnt[2] + 3 and cnt[0] % 2 == 1: return True if cnt[1] <= cnt[2] and cnt[0] % 2 == 0: return True if cnt[2] > 0: if cnt[2] >= cnt[1] + 3 and cnt[0] % 2 == 1: return True if cnt[2] <= cnt[1] and cnt[0] % 2 == 0: return True return False
100ac1
82ff43
Alice and Bob continue their games with stones. There is a row of n stones, and each stone has an associated value. You are given an integer array stones, where stones[i] is the value of the ith stone. Alice and Bob take turns, with Alice starting first. On each turn, the player may remove any stone from stones. The player who removes a stone loses if the sum of the values of all removed stones is divisible by 3. Bob will win automatically if there are no remaining stones (even if it is Alice's turn). Assuming both players play optimally, return true if Alice wins and false if Bob wins.   Example 1: Input: stones = [2,1] Output: true Explanation: The game will be played as follows: - Turn 1: Alice can remove either stone. - Turn 2: Bob removes the remaining stone. The sum of the removed stones is 1 + 2 = 3 and is divisible by 3. Therefore, Bob loses and Alice wins the game. Example 2: Input: stones = [2] Output: false Explanation: Alice will remove the only stone, and the sum of the values on the removed stones is 2. Since all the stones are removed and the sum of values is not divisible by 3, Bob wins the game. Example 3: Input: stones = [5,1,2,4,3] Output: false Explanation: Bob will always win. One possible way for Bob to win is shown below: - Turn 1: Alice can remove the second stone with value 1. Sum of removed stones = 1. - Turn 2: Bob removes the fifth stone with value 3. Sum of removed stones = 1 + 3 = 4. - Turn 3: Alices removes the fourth stone with value 4. Sum of removed stones = 1 + 3 + 4 = 8. - Turn 4: Bob removes the third stone with value 2. Sum of removed stones = 1 + 3 + 4 + 2 = 10. - Turn 5: Alice removes the first stone with value 5. Sum of removed stones = 1 + 3 + 4 + 2 + 5 = 15. Alice loses the game because the sum of the removed stones (15) is divisible by 3. Bob wins the game.   Constraints: 1 <= stones.length <= 100000 1 <= stones[i] <= 10000
from collections import Counter class Solution(object): def stoneGameIX(self, stones): """ :type stones: List[int] :rtype: bool """ n = len(stones) c = Counter(x%3 for x in stones) z = c[0] for x, y in (c[1], c[2]), (c[2], c[1]): # 1 <= x-y <= 2 x = min(x, y+2) y = min(y, x-1) if x>=0 and y>=0 and x+y+z<n and (x+y+z)%2==1: return True return False
e04ad8
beeaf9
Given an integer array nums and two integers left and right, return the number of contiguous non-empty subarrays such that the value of the maximum array element in that subarray is in the range [left, right]. The test cases are generated so that the answer will fit in a 32-bit integer.   Example 1: Input: nums = [2,1,4,3], left = 2, right = 3 Output: 3 Explanation: There are three subarrays that meet the requirements: [2], [2, 1], [3]. Example 2: Input: nums = [2,9,2,5,6], left = 2, right = 8 Output: 7   Constraints: 1 <= nums.length <= 100000 0 <= nums[i] <= 10^9 0 <= left <= right <= 10^9
class Solution(object): def numSubarrayBoundedMax(self, A, L, R): """ :type A: List[int] :type L: int :type R: int :rtype: int """ start=0 end=0 res=0 while end<len(A): while end<len(A) and A[end]<=R: end+=1 res+=(end-start)*(end-start+1)/2 count=0 while start<end: if A[start]<L: count+=1 else: count=0 res-=count start+=1 while end<len(A) and A[end]>R: end+=1 start=end return res
b15b8e
beeaf9
Given an integer array nums and two integers left and right, return the number of contiguous non-empty subarrays such that the value of the maximum array element in that subarray is in the range [left, right]. The test cases are generated so that the answer will fit in a 32-bit integer.   Example 1: Input: nums = [2,1,4,3], left = 2, right = 3 Output: 3 Explanation: There are three subarrays that meet the requirements: [2], [2, 1], [3]. Example 2: Input: nums = [2,9,2,5,6], left = 2, right = 8 Output: 7   Constraints: 1 <= nums.length <= 100000 0 <= nums[i] <= 10^9 0 <= left <= right <= 10^9
class Solution: def numSubarrayBoundedMax(self, A, L, R): """ :type A: List[int] :type L: int :type R: int :rtype: int """ cnt=lambda n:n*(n+1)//2 ans=0 big,small=0,0 for i in range(len(A)): if A[i]>R: ans+=cnt(big)-cnt(small) big,small=0,0 elif A[i]<L: big+=1 small+=1 else: ans-=cnt(small) small=0 big+=1 ans+=cnt(big)-cnt(small) return ans
58fcdd
712b3d
(This problem is an interactive problem.) You may recall that an array arr is a mountain array if and only if: arr.length >= 3 There exists some i with 0 < i < arr.length - 1 such that: arr[0] < arr[1] < ... < arr[i - 1] < arr[i] arr[i] > arr[i + 1] > ... > arr[arr.length - 1] Given a mountain array mountainArr, return the minimum index such that mountainArr.get(index) == target. If such an index does not exist, return -1. You cannot access the mountain array directly. You may only access the array using a MountainArray interface: MountainArray.get(k) returns the element of the array at index k (0-indexed). MountainArray.length() returns the length of the array. Submissions making more than 100 calls to MountainArray.get will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification.   Example 1: Input: array = [1,2,3,4,5,3,1], target = 3 Output: 2 Explanation: 3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2. Example 2: Input: array = [0,1,2,4,2,1], target = 3 Output: -1 Explanation: 3 does not exist in the array, so we return -1.   Constraints: 3 <= mountain_arr.length() <= 10000 0 <= target <= 10^9 0 <= mountain_arr.get(index) <= 10^9
# """ # This is MountainArray's API interface. # You should not implement it, or speculate about its implementation # """ #class MountainArray(object): # def get(self, index): # """ # :type index: int # :rtype int # """ # # def length(self): # """ # :rtype int # """ class Solution(object): def findInMountainArray(self, target, mountain_arr): """ :type target: integer :type mountain_arr: MountainArray :rtype: integer """ n = mountain_arr.length() cache = {} def get(i): if i not in cache: cache[i] = mountain_arr.get(i) return cache[i] # find peak # get(a) < get(a+1) # get(b) > get(b+1) a, b = 0, n - 2 while a + 1 < b: c = (a + b) // 2 if get(c) < get(c+1): a = c else: b = c peak = b # find in ascending # get(a) <= target < get(b) a, b = -1, peak while a + 1 < b: c = (a + b) // 2 if get(c) <= target: a = c else: b = c if a >= 0 and get(a) == target: return a # find in descending # get(a) >= target > get(b) a, b = peak-1, n while a + 1 < b: c = (a + b) // 2 if get(c) >= target: a = c else: b = c if a >= peak and get(a) == target: return a # HTTP 404 NOT FOUND return -1
870b5d
712b3d
(This problem is an interactive problem.) You may recall that an array arr is a mountain array if and only if: arr.length >= 3 There exists some i with 0 < i < arr.length - 1 such that: arr[0] < arr[1] < ... < arr[i - 1] < arr[i] arr[i] > arr[i + 1] > ... > arr[arr.length - 1] Given a mountain array mountainArr, return the minimum index such that mountainArr.get(index) == target. If such an index does not exist, return -1. You cannot access the mountain array directly. You may only access the array using a MountainArray interface: MountainArray.get(k) returns the element of the array at index k (0-indexed). MountainArray.length() returns the length of the array. Submissions making more than 100 calls to MountainArray.get will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification.   Example 1: Input: array = [1,2,3,4,5,3,1], target = 3 Output: 2 Explanation: 3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2. Example 2: Input: array = [0,1,2,4,2,1], target = 3 Output: -1 Explanation: 3 does not exist in the array, so we return -1.   Constraints: 3 <= mountain_arr.length() <= 10000 0 <= target <= 10^9 0 <= mountain_arr.get(index) <= 10^9
# """ # This is MountainArray's API interface. # You should not implement it, or speculate about its implementation # """ #class MountainArray: # def get(self, index: int) -> int: # def length(self) -> int: def first (a, b, crit): if a >= b: return a elif crit(a): return a elif not crit (b-1): return b else: mid = (a + b) // 2 if not crit (mid): return first (mid, b, crit) elif crit (mid-1): return first (a, mid, crit) else: return mid class Solution: def findInMountainArray(self, target: int, mountain_arr: 'MountainArray') -> int: # findpeak # findfront # findback n = mountain_arr.length () peak = first (1, n-1, lambda x: mountain_arr.get (x) > mountain_arr.get (x+1)) front = first (0, peak+1, lambda x: mountain_arr.get (x) >= target) if 0 <= front < n and mountain_arr.get (front) == target: return front back = first (peak+1, n, lambda x: mountain_arr.get (x) <= target) if 0 <= back < n and mountain_arr.get (back) == target: return back return -1
5c5524
d3dba4
You are given a binary string s, and a 2D integer array queries where queries[i] = [firsti, secondi]. For the ith query, find the shortest substring of s whose decimal value, val, yields secondi when bitwise XORed with firsti. In other words, val ^ firsti == secondi. The answer to the ith query is the endpoints (0-indexed) of the substring [lefti, righti] or [-1, -1] if no such substring exists. If there are multiple answers, choose the one with the minimum lefti. Return an array ans where ans[i] = [lefti, righti] is the answer to the ith query. A substring is a contiguous non-empty sequence of characters within a string.   Example 1: Input: s = "101101", queries = [[0,5],[1,2]] Output: [[0,2],[2,3]] Explanation: For the first query the substring in range [0,2] is "101" which has a decimal value of 5, and 5 ^ 0 = 5, hence the answer to the first query is [0,2]. In the second query, the substring in range [2,3] is "11", and has a decimal value of 3, and 3 ^ 1 = 2. So, [2,3] is returned for the second query. Example 2: Input: s = "0101", queries = [[12,8]] Output: [[-1,-1]] Explanation: In this example there is no substring that answers the query, hence [-1,-1] is returned. Example 3: Input: s = "1", queries = [[4,5]] Output: [[0,0]] Explanation: For this example, the substring in range [0,0] has a decimal value of 1, and 1 ^ 4 = 5. So, the answer is [0,0].   Constraints: 1 <= s.length <= 10000 s[i] is either '0' or '1'. 1 <= queries.length <= 100000 0 <= firsti, secondi <= 10^9
class Solution(object): def substringXorQueries(self, s, queries): """ :type s: str :type queries: List[List[int]] :rtype: List[List[int]] """ t, a = {}, [] for i in range(len(s)): if s[i] == '1': v = 0 for j in range(i, min(len(s), i + 30)): v = (v << 1) + (1 if s[j] == '1' else 0) if not v in t: t[v] = [i, j] elif not 0 in t: t[0] = [i, i] for i in range(len(queries)): a.append(t[queries[i][0] ^ queries[i][1]] if queries[i][0] ^ queries[i][1] in t else [-1, -1]) return a
7e5c9f
d3dba4
You are given a binary string s, and a 2D integer array queries where queries[i] = [firsti, secondi]. For the ith query, find the shortest substring of s whose decimal value, val, yields secondi when bitwise XORed with firsti. In other words, val ^ firsti == secondi. The answer to the ith query is the endpoints (0-indexed) of the substring [lefti, righti] or [-1, -1] if no such substring exists. If there are multiple answers, choose the one with the minimum lefti. Return an array ans where ans[i] = [lefti, righti] is the answer to the ith query. A substring is a contiguous non-empty sequence of characters within a string.   Example 1: Input: s = "101101", queries = [[0,5],[1,2]] Output: [[0,2],[2,3]] Explanation: For the first query the substring in range [0,2] is "101" which has a decimal value of 5, and 5 ^ 0 = 5, hence the answer to the first query is [0,2]. In the second query, the substring in range [2,3] is "11", and has a decimal value of 3, and 3 ^ 1 = 2. So, [2,3] is returned for the second query. Example 2: Input: s = "0101", queries = [[12,8]] Output: [[-1,-1]] Explanation: In this example there is no substring that answers the query, hence [-1,-1] is returned. Example 3: Input: s = "1", queries = [[4,5]] Output: [[0,0]] Explanation: For this example, the substring in range [0,0] has a decimal value of 1, and 1 ^ 4 = 5. So, the answer is [0,0].   Constraints: 1 <= s.length <= 10000 s[i] is either '0' or '1'. 1 <= queries.length <= 100000 0 <= firsti, secondi <= 10^9
class Solution: def substringXorQueries(self, s: str, queries: List[List[int]]) -> List[List[int]]: res = [] for fi, se in queries: target = fi ^ se t = "" if target == 0: t = "0" else: while target: tmp = target % 2 t += str(tmp) target //= 2 t = t[::-1] try: st = s.index(t) res.append([st, st + len(t) - 1]) except: res.append([-1, -1]) return res
753f2c
96e8a3
You are given two 0-indexed integer arrays nums1 and nums2, of equal length n. In one operation, you can swap the values of any two indices of nums1. The cost of this operation is the sum of the indices. Find the minimum total cost of performing the given operation any number of times such that nums1[i] != nums2[i] for all 0 <= i <= n - 1 after performing all the operations. Return the minimum total cost such that nums1 and nums2 satisfy the above condition. In case it is not possible, return -1.   Example 1: Input: nums1 = [1,2,3,4,5], nums2 = [1,2,3,4,5] Output: 10 Explanation: One of the ways we can perform the operations is: - Swap values at indices 0 and 3, incurring cost = 0 + 3 = 3. Now, nums1 = [4,2,3,1,5] - Swap values at indices 1 and 2, incurring cost = 1 + 2 = 3. Now, nums1 = [4,3,2,1,5]. - Swap values at indices 0 and 4, incurring cost = 0 + 4 = 4. Now, nums1 =[5,3,2,1,4]. We can see that for each index i, nums1[i] != nums2[i]. The cost required here is 10. Note that there are other ways to swap values, but it can be proven that it is not possible to obtain a cost less than 10. Example 2: Input: nums1 = [2,2,2,1,3], nums2 = [1,2,2,3,3] Output: 10 Explanation: One of the ways we can perform the operations is: - Swap values at indices 2 and 3, incurring cost = 2 + 3 = 5. Now, nums1 = [2,2,1,2,3]. - Swap values at indices 1 and 4, incurring cost = 1 + 4 = 5. Now, nums1 = [2,3,1,2,2]. The total cost needed here is 10, which is the minimum possible. Example 3: Input: nums1 = [1,2,2], nums2 = [1,2,2] Output: -1 Explanation: It can be shown that it is not possible to satisfy the given conditions irrespective of the number of operations we perform. Hence, we return -1.   Constraints: n == nums1.length == nums2.length 1 <= n <= 100000 1 <= nums1[i], nums2[i] <= n
class Solution: def minimumTotalCost(self, nums1: List[int], nums2: List[int]) -> int: cs = collections.Counter(nums1+nums2) if max(cs.values()) > len(nums1) : return -1 to_deal = [i for i in range(len(nums1)) if nums1[i] == nums2[i]] if len(to_deal) == 0 : return 0 cs = collections.Counter([nums1[i] for i in to_deal]) if max(cs.values()) * 2 <= len(to_deal) : # if len(to_deal) % 2 == 0 : return sum(to_deal) # 奇数的话,让标号为0的位置的数多换一下。 mt = max(cs.values()) mti = [t for t in cs if cs[t] == mt][0] its = [] for i in range(len(nums1)) : if not nums1[i]==nums2[i] and not nums1[i] == mti and not nums2[i] == mti : its.append(i) # print(to_deal, its) to_ret = sum(to_deal) to_ret += sum(its[:mt*2-len(to_deal)]) return to_ret
944768
96e8a3
You are given two 0-indexed integer arrays nums1 and nums2, of equal length n. In one operation, you can swap the values of any two indices of nums1. The cost of this operation is the sum of the indices. Find the minimum total cost of performing the given operation any number of times such that nums1[i] != nums2[i] for all 0 <= i <= n - 1 after performing all the operations. Return the minimum total cost such that nums1 and nums2 satisfy the above condition. In case it is not possible, return -1.   Example 1: Input: nums1 = [1,2,3,4,5], nums2 = [1,2,3,4,5] Output: 10 Explanation: One of the ways we can perform the operations is: - Swap values at indices 0 and 3, incurring cost = 0 + 3 = 3. Now, nums1 = [4,2,3,1,5] - Swap values at indices 1 and 2, incurring cost = 1 + 2 = 3. Now, nums1 = [4,3,2,1,5]. - Swap values at indices 0 and 4, incurring cost = 0 + 4 = 4. Now, nums1 =[5,3,2,1,4]. We can see that for each index i, nums1[i] != nums2[i]. The cost required here is 10. Note that there are other ways to swap values, but it can be proven that it is not possible to obtain a cost less than 10. Example 2: Input: nums1 = [2,2,2,1,3], nums2 = [1,2,2,3,3] Output: 10 Explanation: One of the ways we can perform the operations is: - Swap values at indices 2 and 3, incurring cost = 2 + 3 = 5. Now, nums1 = [2,2,1,2,3]. - Swap values at indices 1 and 4, incurring cost = 1 + 4 = 5. Now, nums1 = [2,3,1,2,2]. The total cost needed here is 10, which is the minimum possible. Example 3: Input: nums1 = [1,2,2], nums2 = [1,2,2] Output: -1 Explanation: It can be shown that it is not possible to satisfy the given conditions irrespective of the number of operations we perform. Hence, we return -1.   Constraints: n == nums1.length == nums2.length 1 <= n <= 100000 1 <= nums1[i], nums2[i] <= n
class Solution(object): def minimumTotalCost(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: int """ n=len(nums1) length=0 ind={} count=0 d={} for i in range(n): if nums1[i]==nums2[i]: ind[i]=1 length+=1 count+=i d[nums1[i]]=d.get(nums1[i],0)+2 t=list(d.keys()) for i in t: if d[i]>length: number=i num=d[i] break else: return count for i in range(n): if ind.get(i,0)==0: if nums1[i]!=number and nums2[i]!=number: length+=1 count+=i if num<=length: break else: return -1 return count
266606
6006cb
Alice is a caretaker of n gardens and she wants to plant flowers to maximize the total beauty of all her gardens. You are given a 0-indexed integer array flowers of size n, where flowers[i] is the number of flowers already planted in the ith garden. Flowers that are already planted cannot be removed. You are then given another integer newFlowers, which is the maximum number of flowers that Alice can additionally plant. You are also given the integers target, full, and partial. A garden is considered complete if it has at least target flowers. The total beauty of the gardens is then determined as the sum of the following: The number of complete gardens multiplied by full. The minimum number of flowers in any of the incomplete gardens multiplied by partial. If there are no incomplete gardens, then this value will be 0. Return the maximum total beauty that Alice can obtain after planting at most newFlowers flowers.   Example 1: Input: flowers = [1,3,1,1], newFlowers = 7, target = 6, full = 12, partial = 1 Output: 14 Explanation: Alice can plant - 2 flowers in the 0th garden - 3 flowers in the 1st garden - 1 flower in the 2nd garden - 1 flower in the 3rd garden The gardens will then be [3,6,2,2]. She planted a total of 2 + 3 + 1 + 1 = 7 flowers. There is 1 garden that is complete. The minimum number of flowers in the incomplete gardens is 2. Thus, the total beauty is 1 * 12 + 2 * 1 = 12 + 2 = 14. No other way of planting flowers can obtain a total beauty higher than 14. Example 2: Input: flowers = [2,4,5,3], newFlowers = 10, target = 5, full = 2, partial = 6 Output: 30 Explanation: Alice can plant - 3 flowers in the 0th garden - 0 flowers in the 1st garden - 0 flowers in the 2nd garden - 2 flowers in the 3rd garden The gardens will then be [5,4,5,5]. She planted a total of 3 + 0 + 0 + 2 = 5 flowers. There are 3 gardens that are complete. The minimum number of flowers in the incomplete gardens is 4. Thus, the total beauty is 3 * 2 + 4 * 6 = 6 + 24 = 30. No other way of planting flowers can obtain a total beauty higher than 30. Note that Alice could make all the gardens complete but in this case, she would obtain a lower total beauty.   Constraints: 1 <= flowers.length <= 100000 1 <= flowers[i], target <= 100000 1 <= newFlowers <= 10^10 1 <= full, partial <= 100000
class Solution(object): def maximumBeauty(self, flowers, newFlowers, target, full, partial): """ :type flowers: List[int] :type newFlowers: int :type target: int :type full: int :type partial: int :rtype: int """ g, s, p, q, r = sorted(flowers), 0, [0] * len(flowers), len(flowers) - 1, target - 1 for i in range(len(flowers)): s, p[i] = s + g[i], s + g[i] while True: while q >= 0 and g[q] > r: q -= 1 if q < 0 or (q + 1) * r - newFlowers <= p[q]: break r -= 1 t = 0 if q < 0 else r * partial for i in range(len(flowers) - 1, -1, -1): newFlowers -= max(0, target - g[i]) if newFlowers < 0: break q = min(q, i - 1) while True: while q >= 0 and g[q] > r: q -= 1 if q < 0 or (q + 1) * r - newFlowers <= p[q]: break r -= 1 t = max((len(flowers) - i) * full + (0 if q < 0 else r * partial), t) return t
1e4342
6006cb
Alice is a caretaker of n gardens and she wants to plant flowers to maximize the total beauty of all her gardens. You are given a 0-indexed integer array flowers of size n, where flowers[i] is the number of flowers already planted in the ith garden. Flowers that are already planted cannot be removed. You are then given another integer newFlowers, which is the maximum number of flowers that Alice can additionally plant. You are also given the integers target, full, and partial. A garden is considered complete if it has at least target flowers. The total beauty of the gardens is then determined as the sum of the following: The number of complete gardens multiplied by full. The minimum number of flowers in any of the incomplete gardens multiplied by partial. If there are no incomplete gardens, then this value will be 0. Return the maximum total beauty that Alice can obtain after planting at most newFlowers flowers.   Example 1: Input: flowers = [1,3,1,1], newFlowers = 7, target = 6, full = 12, partial = 1 Output: 14 Explanation: Alice can plant - 2 flowers in the 0th garden - 3 flowers in the 1st garden - 1 flower in the 2nd garden - 1 flower in the 3rd garden The gardens will then be [3,6,2,2]. She planted a total of 2 + 3 + 1 + 1 = 7 flowers. There is 1 garden that is complete. The minimum number of flowers in the incomplete gardens is 2. Thus, the total beauty is 1 * 12 + 2 * 1 = 12 + 2 = 14. No other way of planting flowers can obtain a total beauty higher than 14. Example 2: Input: flowers = [2,4,5,3], newFlowers = 10, target = 5, full = 2, partial = 6 Output: 30 Explanation: Alice can plant - 3 flowers in the 0th garden - 0 flowers in the 1st garden - 0 flowers in the 2nd garden - 2 flowers in the 3rd garden The gardens will then be [5,4,5,5]. She planted a total of 3 + 0 + 0 + 2 = 5 flowers. There are 3 gardens that are complete. The minimum number of flowers in the incomplete gardens is 4. Thus, the total beauty is 3 * 2 + 4 * 6 = 6 + 24 = 30. No other way of planting flowers can obtain a total beauty higher than 30. Note that Alice could make all the gardens complete but in this case, she would obtain a lower total beauty.   Constraints: 1 <= flowers.length <= 100000 1 <= flowers[i], target <= 100000 1 <= newFlowers <= 10^10 1 <= full, partial <= 100000
from sortedcontainers import SortedList class Solution: def maximumBeauty(self, flowers: List[int], newFlowers: int, target: int, full: int, partial: int) -> int: flowers.sort() pref = [0] for x in flowers: pref.append(pref[-1] + x) def getPartial(newFlowers): def isPossible(mn): index = bisect_left(flowers, mn) return (mn * index - pref[index]) <= newFlowers if not flowers: return 0 ret = 0 lo = 0 hi = target - 1 while lo <= hi: mid = (lo + hi) // 2 if isPossible(mid): ret = mid lo = mid + 1 else: hi = mid - 1 return ret * partial numFull = 0 while flowers and flowers[-1] >= target: numFull += 1 flowers.pop() #print('init', numFull, flowers, getPartial(newFlowers)) ans = 0 score = numFull * full + getPartial(newFlowers) ans = max(ans, score) while flowers: x = flowers.pop() assert x < target need = target - x if need <= newFlowers: newFlowers -= need numFull += 1 else: break score = numFull * full + getPartial(newFlowers) #print(numFull, flowers, numFull * full, getPartial(newFlowers), score) ans = max(ans, score) return ans
ece1ad
156f3d
You are given a 0-indexed integer array nums representing the score of students in an exam. The teacher would like to form one non-empty group of students with maximal strength, where the strength of a group of students of indices i0, i1, i2, ... , ik is defined as nums[i0] * nums[i1] * nums[i2] * ... * nums[ik​]. Return the maximum strength of a group the teacher can create.   Example 1: Input: nums = [3,-1,-5,2,5,-9] Output: 1350 Explanation: One way to form a group of maximal strength is to group the students at indices [0,2,3,4,5]. Their strength is 3 * (-5) * 2 * 5 * (-9) = 1350, which we can show is optimal. Example 2: Input: nums = [-4,-5,-4] Output: 20 Explanation: Group the students at indices [0, 1] . Then, we’ll have a resulting strength of 20. We cannot achieve greater strength.   Constraints: 1 <= nums.length <= 13 -9 <= nums[i] <= 9
class Solution: def maxStrength(self, nums: List[int]) -> int: n = len(nums) res = -inf for i in range(1, 1 << n): v = 1 for j in range(n): if (i >> j) & 1: v *= nums[j] res = max(res, v) return res
3c1644
156f3d
You are given a 0-indexed integer array nums representing the score of students in an exam. The teacher would like to form one non-empty group of students with maximal strength, where the strength of a group of students of indices i0, i1, i2, ... , ik is defined as nums[i0] * nums[i1] * nums[i2] * ... * nums[ik​]. Return the maximum strength of a group the teacher can create.   Example 1: Input: nums = [3,-1,-5,2,5,-9] Output: 1350 Explanation: One way to form a group of maximal strength is to group the students at indices [0,2,3,4,5]. Their strength is 3 * (-5) * 2 * 5 * (-9) = 1350, which we can show is optimal. Example 2: Input: nums = [-4,-5,-4] Output: 20 Explanation: Group the students at indices [0, 1] . Then, we’ll have a resulting strength of 20. We cannot achieve greater strength.   Constraints: 1 <= nums.length <= 13 -9 <= nums[i] <= 9
class Solution(object): def maxStrength(self, nums): """ :type nums: List[int] :rtype: int """ n=len(nums) mask=2**n maxx=-10**18 for i in range(1,mask): f=1 for j in range(n): if i&(1<<j)!=0: f*=nums[j] maxx=max(maxx,f) return maxx