inputs
stringlengths 50
14k
| targets
stringlengths 4
655k
|
|---|---|
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 <= 500
1 <= n <= 500
grid consists only of lowercase English letters.
|
class Solution:
def isCycle(self, grid, r, c, visited, pr, pc):
nrow, ncol = len(grid), len(grid[0])
direcs = [(0,1),(0,-1),(-1,0),(1,0)]
visited.add((r, c))
for dr, dc in direcs:
nr, nc = r + dr, c + dc
if 0 <= nr < nrow and 0 <= nc < ncol and grid[nr][nc] == grid[r][c] and not (pr==nr and pc==nc):
if (nr, nc) in visited:
return True
if self.isCycle(grid, nr, nc, visited, r, c):
return True
return False
def containsCycle(self, grid: List[List[str]]) -> bool:
nrow, ncol = len(grid), len(grid[0])
visited = set()
for r in range(nrow):
for c in range(ncol):
if (r, c) in visited:
continue
if self.isCycle(grid, r, c, visited, -1, -1):
return True
return False
|
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 <= 500
1 <= n <= 500
grid consists only of lowercase English letters.
|
class UF:
def __init__(self, m, n):
self.p = {(i, j): (i, j) for i in range(m) for j in range(n)}
def union(self, ti, tj):
pi, pj = self.find(*ti), self.find(*tj)
if pi != pj:
self.p[pj] = pi
return False
return True
def find(self, i, j):
if (i, j) != self.p[i,j]:
self.p[i,j] = self.find(*self.p[i,j])
return self.p[i,j]
class Solution:
def containsCycle(self, grid: List[List[str]]) -> bool:
# 如何定义cycle:同一个点的两个不同方向的path,最终汇聚到非自身的同一点
m, n = len(grid), len(grid[0])
uf = UF(m, n)
for i in range(m):
for j in range(n):
if i > 0 and grid[i][j] == grid[i-1][j]:
if uf.union(tuple([i-1, j]), tuple([i, j])): return True
if j > 0 and grid[i][j] == grid[i][j-1]:
if uf.union(tuple([i, j-1]), tuple([i, j])): return True
return False
|
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 <= 500
1 <= n <= 500
grid consists only of lowercase English letters.
|
class DSU:
def __init__(self, N):
self.par = list(range(N))
self.sz = [1] * N
def find(self, x):
if self.par[x] != x:
self.par[x] = self.find(self.par[x])
return self.par[x]
def union(self, x, y):
xr, yr = self.find(x), self.find(y)
if xr == yr:
return False
if self.sz[xr] < self.sz[yr]:
xr, yr = yr, xr
self.par[yr] = xr
self.sz[xr] += self.sz[yr]
self.sz[yr] = self.sz[xr]
return True
class Solution:
def containsCycle(self, A):
R, C = len(A), len(A[0])
def encode(r, c):
return r * C + c
dsu = DSU(R * C)
for r in range(R):
for c in range(C):
if c + 1 < C and A[r][c] == A[r][c+1]:
if not dsu.union(encode(r, c), encode(r, c + 1)):
return True
if r + 1 < R and A[r][c] == A[r+1][c]:
if not dsu.union(encode(r, c), encode(r + 1, c)):
return True
return False
|
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 <= 500
1 <= n <= 500
grid consists only of lowercase English letters.
|
import collections
class Solution:
def containsCycle(self, grid: List[List[str]]) -> bool:
def find(pos):
if parents[pos] != pos:
parents[pos] = find(parents[pos])
return parents[pos]
def union(pos1, pos2):
parent1, parent2 = find(pos1), find(pos2)
if parent1 != parent2:
if ranks[pos1] > ranks[pos2]:
parents[pos2] = pos1
else:
parents[pos1] = pos2
if ranks[pos1] == ranks[pos2]:
ranks[pos1] += 1
rows, cols = len(grid), len(grid[0])
parents = {(i, j): (i, j) for i in range(rows) for j in range(cols)}
ranks = collections.Counter()
for i, row in enumerate(grid):
for j, letter in enumerate(row):
if i > 0 and j > 0 and grid[i-1][j] == grid[i][j-1] == letter and find((i-1, j)) == find((i, j-1)):
return True
for r, c in (i - 1, j), (i, j - 1):
if 0 <= r < rows and 0 <= c < cols and grid[r][c] == letter:
union((i, j), (r, c))
return False
|
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 <= 500
1 <= n <= 500
grid consists only of lowercase English letters.
|
class Solution:
def rec(self,i,j,char,prev):
if self.grid[i][j] != char:
return False
if self.matrix[i][j]:
return True
else:
self.matrix[i][j] = True
l = (i,j-1)
r = (i,j+1)
u = (i-1,j)
d = (i+1,j)
for c in [l,r,u,d]:
if 0<=c[0]<self.row and 0<=c[1]<self.col and c != prev:
if self.rec(c[0],c[1], char, (i,j)):
return True
return False
def containsCycle(self, grid: List[List[str]]) -> bool:
self.grid = grid
self.row = len(grid)
self.col = len(grid[0])
self.matrix = [ [False for i in range(self.col)] for j in range(self.row) ]
for i in range(self.row):
for j in range(self.col):
if not self.matrix[i][j]:
if self.rec(i,j, grid[i][j],0):
return True
return False
|
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 <= 500
1 <= n <= 500
grid consists only of lowercase English letters.
|
class Solution:
def containsCycle(self, grid: List[List[str]]) -> bool:
m, n = len(grid), len(grid[0])
dsu = DUS()
for i in range(m):
for j in range(n):
if i == 0 and j == 0:
continue
if j != 0 and grid[i][j] == grid[i][j - 1]:
dsu.union((i, j), (i, j - 1))
if i != 0 and grid[i][j] == grid[i - 1][j]:
if dsu.find((i,j)) == dsu.find((i - 1, j)):
return True
dsu.union((i, j), (i - 1, j))
return False
class DUS:
def __init__(self):
self.father = {}
def find(self, a):
self.father.setdefault(a, a)
if a != self.father[a]:
self.father[a] = self.find(self.father[a])
return self.father[a]
def union(self, a, b):
_a = self.find(a)
_b = self.find(b)
if _a != _b:
self.father[_a] = _b
|
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 <= 500
1 <= n <= 500
grid consists only of lowercase English letters.
|
class Solution:
def containsCycle(self, grid: List[List[str]]) -> bool:
m, n = len(grid), len(grid[0])
uf = {(i, j): (i, j) for i in range(m) for j in range(n)}
def find(pos):
if pos != uf[pos]:
uf[pos] = find(uf[pos])
return uf[pos]
def union(pos1, pos2):
root1 = find(pos1)
root2 = find(pos2)
if root1 != root2:
uf[root1] = root2
for i in range(m):
for j in range(n):
if i > 0 and j > 0 and find((i - 1, j)) == find((i, j - 1)) and grid[i][j] == grid[i-1][j] == grid[i][j-1]:
return True
if i > 0 and grid[i][j] == grid[i-1][j]:
union((i, j), (i - 1, j))
if j > 0 and grid[i][j] == grid[i][j-1]:
union((i, j), (i, j - 1))
return False
|
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 <= 500
1 <= n <= 500
grid consists only of lowercase English letters.
|
class UnionFind:
def __init__(self, m: int, n: int):
self.rank = collections.Counter()
self.parent = {(i, j): (i, j) for i in range(m) for j in range(n)}
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union(self, x, y):
px = self.find(x)
py = self.find(y)
if px == py:
return
if self.rank[py] > self.rank[px]:
px, py = py, px
if self.rank[py] == self.rank[px]:
self.rank[px] += 1
self.parent[py] = px
class Solution:
def containsCycle(self, grid: List[List[str]]) -> bool:
rows, cols = len(grid), len(grid[0])
uf = UnionFind(rows, cols)
for i, row in enumerate(grid):
for j, letter in enumerate(row):
if (i > 0 and j > 0 and
grid[i - 1][j] == grid[i][j - 1] == letter and
uf.find((i - 1, j)) == uf.find((i, j - 1))):
return True
for r, c in (i - 1, j), (i, j - 1):
if 0 <= r and 0 <= c and grid[r][c] == letter:
uf.union((i, j), (r, c))
return False
|
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 <= 500
1 <= n <= 500
grid consists only of lowercase English letters.
|
class Solution:
def containsCycle(self, grid: List[List[str]]) -> bool:
# dfs, remember parent
self.m, self.n = len(grid), len(grid[0])
nei = [(0, 1), (0, -1),(-1, 0), (1, 0)]
memo = set()
def dfs(i, j, p):
# print(i, j, p, memo)
if (i, j) in memo: return True
memo.add((i, j))
for ne in nei:
x, y = i + ne[0], j + ne[1]
if 0 <= x < self.m and 0 <= y < self.n and (x, y) != p and grid[i][j] == grid[x][y]:
if dfs(x, y, (i, j)): return True
return False
for i in range(self.m):
for j in range(self.n):
if (i, j) not in memo:
if dfs(i, j, (-1, -1)): return True
return False
|
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 <= 500
1 <= n <= 500
grid consists only of lowercase English letters.
|
from collections import defaultdict
class Solution:
DELTA = [(0,-1),(0,1),(-1,0),(1,0)]
def containsCycle(self, grid: List[List[str]]) -> bool:
def dfsCycle(grid, R, C, p_r, p_c, r, c, visited, grp, grp_num):
if (r, c) in grp[grp_num]:
return True
# print('p_r=', p_r, 'p_c=', p_c)
# check 4 directions
visited.add((r,c))
grp[grp_num].add((r,c))
result = False
for d in Solution.DELTA:
n_r = r + d[0]
n_c = c + d[1]
# print('n_r=', n_r, 'n_c=', n_c)
if 0 <= n_r < R and 0 <= n_c < C and not (p_r == n_r and p_c == n_c) and grid[n_r][n_c] == grid[r][c]:
result |= dfsCycle(grid, R, C, r, c, n_r, n_c, visited, grp, grp_num)
if result:
break
return result
R = len(grid)
C = len(grid[0])
visited = set()
grp_num = 0
grp = defaultdict(set)
for r in range(R):
for c in range(C):
if (r,c) not in visited:
grp_num += 1
# print('r=', r, 'c=', c, grid[r][c])
if dfsCycle(grid, R, C, r, c, r, c, visited, grp, grp_num):
return True
# print(grid)
return False
|
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 <= 500
1 <= n <= 500
grid consists only of lowercase English letters.
|
class Solution:
def containsCycle(self, grid: List[List[str]]) -> bool:
h, w = len(grid), len(grid[0])
#------------------------------------------
def in_range(x, y):
return (0 <= x < w) and (0 <= y < h)
#------------------------------------------
def four_neighbors(x, y):
for dx, dy in {(+1, 0), (-1, 0), (0, +1), (0, -1)}:
next_x, next_y = x + dx, y + dy
if in_range(next_x, next_y):
yield (next_x, next_y)
#------------------------------------------
def dfs(x, y, prev_x, prev_y, grid):
if grid[y][x] == dfs.cur_symbol:
# this grid has a cycle with current symbol
return True
# mark to uppercase letter as visited
grid[y][x] = dfs.cur_symbol
for next_x, next_y in four_neighbors(x, y):
if (next_x, next_y) == (prev_x, prev_y):
# avoid backward visit
continue
elif grid[next_y][next_x].upper() != dfs.cur_symbol:
# different symbol
continue
if dfs(next_x, next_y, x, y, grid): return True
#print(f'terminate with {x} {y} {grid[y][x]}')
return False
#------------------------------------------
failed_symbol = set()
for y in range(h):
#for y in reversed(range(h)):
for x in range(w):
#for x in reversed(range(w)):
dfs.cur_symbol = grid[y][x]
if dfs.cur_symbol in failed_symbol:
# skip search on failed symbol
continue
dfs.cur_symbol = grid[y][x].upper()
if dfs(x,y,-1,-1, grid):
return True
else:
failed_symbol.add( dfs.cur_symbol )
return False
|
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 <= 500
1 <= n <= 500
grid consists only of lowercase English letters.
|
class Solution:
def containsCycle(self, grid: List[List[str]]) -> bool:
m, n = len(grid), len(grid[0])
ve = collections.defaultdict(set)
for i, row in enumerate(grid):
for j, val in enumerate(row):
ve[val].add((i,j))
# print(ve)
dxy = [(-1,0), (1,0), (0,-1), (0,1)]
def check(k):
visiting = set()
visited = set()
v = ve[k]
def dfs(curr, prev):
if curr in visiting: return True
visiting.add(curr)
x,y = curr
for dx, dy in dxy:
x2,y2 = x+dx, y+dy
if 0 <= x2 < m and 0 <= y2 < n and (x2,y2) != prev and (x2,y2) in v:
# print((x2,y2), curr)
if dfs((x2,y2), curr): return True
visiting.remove(curr)
visited.add(curr)
return False
for a in v:
if a not in visited:
if dfs(a, None): return True
return False
for k in ve:
if check(k): return True
return False
|
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 <= 500
1 <= n <= 500
grid consists only of lowercase English letters.
|
class Solution:
def containsCycle(self, grid: List[List[str]]) -> bool:
visited = set()
def dfs(x, y, parent):
if (x, y) in visited:
return True
visited.add((x, y))
c = grid[x][y]
for dx, dy in [[0, -1], [0, 1], [-1, 0], [1, 0]]:
nx, ny = dx + x, dy + y
if 0 <= nx < len(grid) and 0 <= ny < len(grid[0]) and grid[nx][ny] == c and [nx, ny] != parent:
if dfs(nx, ny, [x, y]):
return True
return False
for x in range(len(grid)):
for y in range(len(grid[0])):
if (x, y) not in visited and dfs(x, y, [-1, -1]):
return True
return False
|
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 <= 500
1 <= n <= 500
grid consists only of lowercase English letters.
|
class Solution:
def containsCycle(self, grid: List[List[str]]) -> bool:
visited = set()
n, m = len(grid), len(grid[0])
directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]
def dfs(i, j, pre_i, pre_j):
visited.add((i, j))
for x, y in directions:
if 0 <= x + i < n and 0 <= y + j < m and grid[i][j] == grid[i + x][j + y] and (i + x != pre_i or j + y != pre_j):
if (i + x, j + y) in visited or dfs(i + x, j + y, i, j):
return True
return False
for i in range(n):
for j in range(m):
if (i, j) not in visited:
if dfs(i, j, -1, -1):
return True
return False
|
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 <= 500
1 <= n <= 500
grid consists only of lowercase English letters.
|
class Solution:
def containsCycle(self, grid: List[List[str]]) -> bool:
n = len(grid)
m = len(grid[0])
node_par = {}
for i in range(n):
for j in range(m):
node_par[(i, j)] = (i, j)
dxdys = ((0, 1), (0, -1), (1, 0), (-1, 0))
def find_par(par):
path = []
while node_par[par] != par:
path.append(par)
par = node_par[par]
for tmp in path:
node_par[tmp] = par
return par
for x in range(n):
for y in range(m):
if (x + y) % 2:
continue
for dx, dy in dxdys:
x_new, y_new = x + dx, y + dy
if not (0 <= x_new < n and 0 <= y_new < m) or grid[x_new][y_new] != grid[x][y]:
continue
curr_par = find_par((x, y))
new_par = find_par((x_new, y_new))
if curr_par == new_par:
return True
node_par[curr_par] = new_par
return False
|
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 <= 500
1 <= n <= 500
grid consists only of lowercase English letters.
|
from collections import deque
class Solution:
def __init__(self):
self.locs = defaultdict(set)
self.grid = []
def isValid(self, i, j):
return i >= 0 and i < len(self.grid) and j >= 0 and j < len(self.grid[i])
def hasCycle(self, l):
seen = set()
todo = deque([])
around = [[0, 1], [0, -1], [1, 0], [-1, 0]]
for x in l:
if x not in seen:
todo.append([(-1, -1), x])
while todo:
node = todo.popleft()
cur = node[1]
fr = node[0]
if cur in seen:
return True
seen.add(cur)
for x in around:
test = (cur[0] + x[0], cur[1] + x[1])
if self.isValid(test[0], test[1]) and test in l and not test == fr:
todo.append([cur, test])
return False
def containsCycle(self, grid: List[List[str]]) -> bool:
self.grid = grid
for x in range(len(grid)):
for y in range(len(grid[x])):
self.locs[grid[x][y]].add((x, y))
for x in list(self.locs.keys()):
if self.hasCycle(self.locs[x]):
return True
return False
|
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 <= 500
1 <= n <= 500
grid consists only of lowercase English letters.
|
class Solution:
def containsCycle(self, grid: List[List[str]]) -> bool:
# union find
W, H = len(grid[0]), len(grid)
parent = list(range(W * H))
rank = [0] * (W * H)
def find(x):
if parent[x] != x:
parent[x] = find(parent[x])
return parent[x]
def union(x, y):
px, py = find(x), find(y)
if px != py:
if rank[px] > rank[py]:
parent[py] = px
elif rank[px] < rank[py]:
parent[px] = py
else:
parent[px] = py
rank[py] += 1
for x in range(H):
for y in range(W):
if x and y and grid[x][y] == grid[x - 1][y] == grid[x][y - 1] and find((x - 1) * W + y) == find(x * W + y - 1):
return True
for dx, dy in [(0, -1), (-1, 0)]:
nx, ny = x + dx, y + dy
if 0 <= nx < H and 0 <= ny < W and grid[nx][ny] == grid[x][y]:
union(x * W + y, nx * W + ny)
return False
def containsCycle_dfs(self, grid: List[List[str]]) -> bool:
W, H = len(grid[0]), len(grid)
visited = [[0] * W for _ in range(H)]
def search(x, y, target, px, py):
nonlocal grid, W, H, visited
visited[x][y] = 1
for dx, dy in [(0, 1), (1, 0), (-1, 0), (0, -1)]:
nx, ny = x + dx, y + dy
if 0 <= nx < H and 0 <= ny < W and grid[nx][ny] == target:
if visited[nx][ny]:
if nx == px and ny == py:
continue
return True
if search(nx, ny, target, x, y):
return True
return False
for x in range(H):
for y in range(W):
if not visited[x][y]:
if search(x, y, grid[x][y], None, None):
return True
return False
|
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 <= 500
1 <= n <= 500
grid consists only of lowercase English letters.
|
class Solution:
def containsCycle(self, grid: List[List[str]]) -> bool:
visited = set()
m = len(grid)
if m==1: return False
n = len(grid[0])
dirs = [(0,-1),(-1,0),(0,1),(1,0)]
def dfs(prev, curr):
if curr in visited: return True
visited.add(curr)
for dirn in dirs:
nei = (dirn[0]+curr[0], dirn[1]+curr[1])
if 0<=nei[0]<m and 0<=nei[1]<n and nei != prev and grid[nei[0]][nei[1]] == grid[curr[0]][curr[1]]:
if dfs(curr, nei): return True
return False
for i in range(m):
for j in range(n):
if (i,j) not in visited:
if dfs(None, (i,j)): return True
return False
|
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 <= 500
1 <= n <= 500
grid consists only of lowercase English letters.
|
class DSU:
def __init__(self, n):
self.par = list(range(n))
self.count = [1]*n
def find(self, u):
if u != self.par[u]:
self.par[u] = self.find(self.par[u])
return self.par[u]
def union(self, u, v):
p1, p2 = self.find(u), self.find(v)
if p1 == p2:
return False
if self.count[p1] < self.count[p2]:
p1, p2 = p2, p1
self.count[p1] += self.count[p2]
self.count[p2] = self.count[p1]
self.par[p2] = p1
return True
class Solution:
def containsCycle(self, grid: List[List[str]]) -> bool:
# dsu for each cell
m, n = len(grid), len(grid[0])
dsu = DSU(m*n)
for i in range(m):
for j in range(n):
for p,q in [(i+1,j), (i,j+1)]:
if 0 <= p < m and 0 <= q < n and grid[i][j] == grid[p][q]:
if not dsu.union(i*n+j, p*n+q):
return True
print((dsu.count))
return False
|
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 <= 500
1 <= n <= 500
grid consists only of lowercase English letters.
|
class Solution:
def search_cycle(self, grid, i, j, parents):
key = grid[i][j]
parents[i, j] = (None, None)
nodes = [(i, j)]
visited = set()
while len(nodes):
i, j = nodes.pop()
visited.add((i, j))
pi, pj = parents[i, j]
for ci, cj in [
(i+1, j),
(i-1, j),
(i, j+1),
(i, j-1),
]:
in_range = 0<=ci<len(grid) and 0<=cj<len(grid[ci])
is_same_key = in_range and grid[ci][cj] == key
if ci == pi and cj == pj:
continue
if in_range and is_same_key:
if (ci, cj) in visited:
return True
parents[ci, cj] = (i, j)
nodes.append((ci, cj))
return False
def containsCycle(self, grid: List[List[str]]) -> bool:
parents = {}
for i in range(len(grid)):
for j in range(len(grid[i])):
if (i, j) in parents:
continue
is_cycle = self.search_cycle(grid, i, j, parents)
if is_cycle:
return True
return False
|
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 <= 500
1 <= n <= 500
grid consists only of lowercase English letters.
|
class Solution:
def containsCycle(self, g: List[List[str]]) -> bool:
r = len(g)
c = len(g[0])
cc = {}
def root(x):
if cc[x] != x:
cc[x] = root(cc[x])
return cc[x]
def join(x, y):
rx = root(x)
ry = root(y)
if rx != ry:
cc[rx] = ry
return rx != ry
for i in range(r):
for j in range(c):
cc[i,j] = (i,j)
for i in range(r):
for j in range(c):
for di, dj in [[0,1], [1,0]]:
ni,nj = i + di, j + dj
if 0 <= ni < r and 0 <= nj < c and g[i][j] == g[ni][nj]:
if not join((i,j), (ni,nj)):
return True
return False
|
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 <= 500
1 <= n <= 500
grid consists only of lowercase English letters.
|
class Solution:
def containsCycle(self, grid: List[List[str]]) -> bool:
R, C = len(grid), len(grid[0])
UF = {}
def find(u):
if UF[u] != u:
UF[u] = find(UF[u])
return UF[u]
def union(u, v):
UF.setdefault(u, u)
UF.setdefault(v, v)
UF[find(u)] = find(v)
for i in range(R):
for j in range(C):
if i > 0 and grid[i][j] == grid[i - 1][j]:
if (i, j) in UF and (i - 1, j) in UF and find((i, j)) == find((i - 1, j)): return True
union((i, j), (i - 1, j))
if j > 0 and grid[i][j] == grid[i][j - 1]:
if (i, j) in UF and (i, j - 1) in UF and find((i, j)) == find((i, j - 1)): return True
union((i, j), (i, j - 1))
return False
|
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 <= 500
1 <= n <= 500
grid consists only of lowercase English letters.
|
import sys
sys.setrecursionlimit(250000)
class Solution:
def containsCycle(self, grid: List[List[str]]) -> bool:
m, n = len(grid), len(grid[0])
def valid(x, y):
if x < m and x >= 0 and y < n and y >= 0:
return True
else:
return False
def dfs(x, y, parent_x, parent_y):
visit[x][y] = 1
for d in ((0, 1), (0, -1), (-1, 0), (1, 0)):
new_x = x + d[0]
new_y = y + d[1]
if valid(new_x, new_y) and grid[new_x][new_y] == grid[x][y] and (not (parent_x == new_x and parent_y == new_y)):
if visit[new_x][new_y] == 1:
return True
else:
cur = dfs(new_x, new_y, x, y)
if cur:
return True
return False
visit = [[0 for _ in range(n)] for _ in range(m)]
res = False
for i in range(m):
if res:
return True
for j in range(n):
if visit[i][j] == 0:
res = dfs(i, j, -1, -1)
if res:
return True
return False
|
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 <= 500
1 <= n <= 500
grid consists only of lowercase English letters.
|
import collections
class Solution:
def containsCycle(self, grid: List[List[str]]) -> bool:
'''
# dfs, TLE. I think bfs will leads to TLE as well.
rows, cols = len(grid), len(grid[0])
def dfs(ch, s_r, s_c, row, col, seen, leng):
for dr, dc in [[1, 0],[0, -1], [0, 1], [-1, 0]]:
r, c = row + dr, col + dc
if leng >= 4 and (r, c) == (s_r, s_c):
return True
if 0 <= r < rows and 0 <= c < cols and grid[r][c] == ch and (r, c) not in seen and dfs(ch, s_r, s_c, r, c, seen | set([(r, c)]), leng + 1):
return True
return False
for r in range(rows - 1):
for c in range(cols - 1):
if grid[r][c] == grid[r + 1][c] == grid[r][c + 1]:
if dfs(grid[r][c], r, c, r, c, set([(r, c)]), 1):
return True
return False
'''
# Union Find, when you reach a char which is the same as current char and the two share the same
# ancestor, then there is a ring
rows, cols = len(grid), len(grid[0])
seen = set()
ancestors = dict()
for r in range(rows):
for c in range(cols):
ancestors[(r, c)] = (r, c)
def find(x, y):
if ancestors[(x, y)] != (x, y):
xx, yy = ancestors[(x, y)]
ancestors[(x, y)] = find(xx, yy)
return ancestors[(x, y)]
def union(x1, y1, x2, y2):
# (x2, y2) is the new char that should be added to the group that (x1, y1) belongs to
ancestors[find(x2, y2)] = find(x1, y1)
for r in range(rows):
for c in range(cols):
if r == 0 and c == 0:
continue
if r > 0 and c > 0 and grid[r - 1][c] == grid[r][c - 1] == grid[r][c] and find(r - 1, c) == find(r, c - 1):
return True
if c > 0 and grid[r][c - 1] == grid[r][c]:
union(r, c - 1, r, c)
if r > 0 and grid[r - 1][c] == grid[r][c]:
union(r, c, r - 1, c)
return False
'''
[[\"a\",\"a\",\"a\",\"a\"],[\"a\",\"b\",\"b\",\"a\"],[\"a\",\"b\",\"b\",\"a\"],[\"a\",\"a\",\"a\",\"a\"]]
[[\"c\",\"c\",\"c\",\"a\"],[\"c\",\"d\",\"c\",\"c\"],[\"c\",\"c\",\"e\",\"c\"],[\"f\",\"c\",\"c\",\"c\"]]
[[\"a\",\"b\",\"b\"],[\"b\",\"z\",\"b\"],[\"b\",\"b\",\"a\"]]
[[\"d\",\"b\",\"b\"],[\"c\",\"a\",\"a\"],[\"b\",\"a\",\"c\"],[\"c\",\"c\",\"c\"],[\"d\",\"d\",\"a\"]]
'''
|
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 <= 500
1 <= n <= 500
grid consists only of lowercase English letters.
|
class Solution:
def containsCycle(self, grid: List[List[str]]) -> bool:
return self.unionfind(grid)
'''
self.grid = grid
self.m = len(grid)
self.n = len(grid[0])
self.visited = set()
for i in range(self.m):
for j in range(self.n):
if (i,j) not in self.visited:
if self.bfs((i,j), (-1,-1)):
return True
return False
'''
def find(self, node):
if self.parent[node[0]][node[1]] == node:
return node
else:
p = self.find(self.parent[node[0]][node[1]])
self.parent[node[0]][node[1]] = p
return(p)
def union(self, node1, node2):
p1 = self.find(node1)
p2 = self.find(node2)
if self.rank[p1[0]][p1[1]] > self.rank[p2[0]][p2[1]]:
self.parent[p2[0]][p2[1]] = p1
elif self.rank[p2[0]][p2[1]] > self.rank[p1[0]][p1[1]]:
self.parent[p1[0]][p1[1]] = p2
else:
self.parent[p1[0]][p1[1]] = p2
self.rank[p2[0]][p2[1]] += 1
def unionfind(self,g):
nrow, ncol = len(g), len(g[0])
self.parent = []
self.rank = [[1]*ncol for _ in range(nrow)]
for i in range(nrow):
self.parent.append([(i,j) for j in range(ncol)])
for i in range(nrow):
for j in range(ncol):
if i+1 < nrow and g[i][j] == g[i+1][j]:
if self.find((i,j)) == self.find((i+1, j)):
return True
self.union((i,j), (i+1, j))
if j+1 < ncol and g[i][j] == g[i][j+1]:
if self.find((i,j)) == self.find((i, j+1)):
return True
self.union((i,j), (i, j+1))
return False
def cycle(self, current, parent):
if current in self.visited:
return True
self.visited.add(current)
i,j = current
neb = [(i+1,j), (i-1,j), (i, j+1), (i, j-1)]
for ne in neb:
ni, nj = ne
if ne != parent and ni >= 0 and ni < self.m and nj >=0 and nj < self.n and self.grid[ni][nj] == self.grid[i][j]:
#print(ne)
if self.cycle((ni, nj), current):
return True
return False
def bfs(self, current, parent):
if current in self.visited:
return True
q = []
q.append((current, parent))
self.visited.add(current)
while q:
node, par = q.pop()
#print(node)
#print(par)
i,j = node
neb = [(i+1,j),(i-1,j), (i, j+1), (i,j-1)]
for ni,nj in neb:
if ni >= 0 and ni < self.m and nj >=0 and nj < self.n and self.grid[ni][nj] == self.grid[i][j] and (ni, nj) != par:
if (ni, nj) in self.visited:
return True
q.append(((ni,nj), (i,j)))
self.visited.add((ni,nj))
return False
|
A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum.
Given a row x col grid of integers, how many 3 x 3 "magic square" subgrids are there? (Each subgrid is contiguous).
Example 1:
Input: grid = [[4,3,8,4],[9,5,1,9],[2,7,6,2]]
Output: 1
Explanation:
The following subgrid is a 3 x 3 magic square:
while this one is not:
In total, there is only one magic square inside the given grid.
Example 2:
Input: grid = [[8]]
Output: 0
Example 3:
Input: grid = [[4,4],[3,3]]
Output: 0
Example 4:
Input: grid = [[4,7,8],[9,5,1],[2,3,6]]
Output: 0
Constraints:
row == grid.length
col == grid[i].length
1 <= row, col <= 10
0 <= grid[i][j] <= 15
|
class Solution:
def numMagicSquaresInside(self, grid: List[List[int]]) -> int:
# slide window and call isMagicSquare
if len(grid) < 3 or len(grid[0]) < 3:
return 0
rows = len(grid)
cols = len(grid[0])
magic_squares = 0
for i in range(rows - 2):
for j in range(cols - 2):
window = [tmp[j:j + 3] for tmp in grid[i: i + 3]]
if self.isMagicSquare(window):
magic_squares += 1
return magic_squares
def isMagicSquare(self, square: List[List[int]]) -> bool:
target = square[0][0] + square[0][1] + square[0][2]
seen = {}
print(square)
# check rows
for row in square:
tmp = 0
for i in row:
tmp += i
if i in seen or i > 9 or i < 1:
return False
else:
seen[i] = 1
if tmp != target:
return False
# check cols
for i in range(3):
tmp = 0
for row in square:
tmp += row[i]
if tmp != target:
return False
# check left to right diag
tmp = 0
for i in range(3):
tmp += square[i][i]
if tmp != target:
return False
# check right to left diag
tmp = 0
for i in range(3):
tmp += square[i][2 - i]
if tmp != target:
return False
return True
|
A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum.
Given a row x col grid of integers, how many 3 x 3 "magic square" subgrids are there? (Each subgrid is contiguous).
Example 1:
Input: grid = [[4,3,8,4],[9,5,1,9],[2,7,6,2]]
Output: 1
Explanation:
The following subgrid is a 3 x 3 magic square:
while this one is not:
In total, there is only one magic square inside the given grid.
Example 2:
Input: grid = [[8]]
Output: 0
Example 3:
Input: grid = [[4,4],[3,3]]
Output: 0
Example 4:
Input: grid = [[4,7,8],[9,5,1],[2,3,6]]
Output: 0
Constraints:
row == grid.length
col == grid[i].length
1 <= row, col <= 10
0 <= grid[i][j] <= 15
|
class Solution:
def isMagicSquare(self, grid):
'''
Check whether the given grid is a magic square
'''
# Check the elements
flat = [num for row in grid for num in row]
if sorted(flat) != [1, 2, 3, 4, 5, 6, 7, 8, 9]:
return False
# Check the row, column and diagnal sums
row_sums = [sum(row) for row in grid]
col_sums = [sum([row[i] for row in grid]) for i in range(3)]
diag_sums = [sum([grid[i][i] for i in range(3)]), (grid[0][2] + grid[1][1] + grid[2][0])]
row_sums.extend(col_sums)
row_sums.extend(diag_sums)
return len(set(row_sums)) == 1
def numMagicSquaresInside(self, grid: List[List[int]]) -> int:
# 9:37 --> 9:52 --> 10:31 9/14/20
cnt = 0
# Construct the 3x3 square
for i in range(len(grid)-2):
for j in range(len(grid)-2):
temp_grid = [grid[i+k][j:j+3] for k in range(3)]
if self.isMagicSquare(temp_grid):
cnt += 1
return cnt
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
from typing import *
from heapq import heappop, heappush
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
N = len(quality)
heap_quality = []
workers = [i for i in range(N)]
workers = sorted(workers, key=lambda x: wage[x] / quality[x])
sum_quality = 0
for i in range(K):
heappush(heap_quality, -quality[workers[i]])
sum_quality += quality[workers[i]]
ans = sum_quality * (wage[workers[K - 1]] / quality[workers[K - 1]])
for i in range(K, N):
heappush(heap_quality, -quality[workers[i]])
sum_quality += quality[workers[i]]
sum_quality += heappop(heap_quality) # negative quality value
ans = min(ans, sum_quality * (wage[workers[i]] / quality[workers[i]]))
return ans
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
workers = sorted([float(w) / q, q] for w, q in zip(wage, quality))
res = float('inf')
qsum = 0
heap = []
for r, q in workers:
heapq.heappush(heap, -q)
qsum += q
if len(heap) > K: qsum += heapq.heappop(heap)
if len(heap) == K: res = min(res, qsum * r)
return res
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
from fractions import Fraction
workers = sorted((Fraction(w, q), q, w)
for q, w in zip(quality, wage))
ans = float('inf')
pool = []
sumq = 0
for ratio, q, w in workers:
heapq.heappush(pool, -q)
sumq += q
if len(pool) > K:
sumq += heapq.heappop(pool)
if len(pool) == K:
ans = min(ans, ratio * sumq)
return float(ans)
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution(object):
def mincostToHireWorkers(self, quality, wage, K):
from fractions import Fraction
workers = sorted((Fraction(w, q), q, w)
for q, w in zip(quality, wage))
print(workers)
ans = float('inf')
pool = []
sumq = 0
for ratio, q, w in workers:
heapq.heappush(pool, -q)
sumq += q
if len(pool) > K:
sumq += heapq.heappop(pool)
if len(pool) == K:
ans = min(ans, ratio * sumq)
return float(ans)
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
from fractions import Fraction
workers = sorted((Fraction(w, q), q, w)
for q, w in zip(quality, wage))
print(workers)
ans = float('inf')
pool = []
sumq = 0
for ratio, q, w in workers:
heapq.heappush(pool, -q)
#print(pool)
sumq += q
if len(pool) > K:
sumq += heapq.heappop(pool)
#print(pool)
if len(pool) == K:
ans = min(ans, ratio * sumq)
#print(sumq)
#print(pool)
return float(ans)
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
import heapq
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
n_workers = len(wage)
pairs = [None]*n_workers # (quality, wage/quality)
for i in range(n_workers):
pairs[i] = (quality[i], wage[i]/quality[i])
pairs = sorted(pairs, key=lambda x: (x[1])) # sort dec by ratio then quality
# incorrect solution
# max_q = pairs[i:i+K]
# for i in range(n_workers-K+1):
# min_cost = min(min_cost, self.cost(pairs[i:i+K]))
sum_q = sum([p[0] for p in pairs[0:K]])
maxheap_q = [-p[0] for p in pairs[0:K]] # use minus to create max heap
heapq.heapify(maxheap_q)
min_cost = sum_q * pairs[K-1][1]
for i in range(K, n_workers):
sum_q = sum_q - (-min(maxheap_q)) + pairs[i][0]
min_cost = min(min_cost, sum_q * pairs[i][1])
heapq.heapreplace(maxheap_q, -pairs[i][0])
# print(sum_q * pairs[i][1])
return min_cost
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
ratios = [[wi / qi, qi] for wi, qi in zip(wage, quality)]
ratios.sort(reverse=True)
res = float('inf')
quality.sort()
for ratio, q in ratios:
quality.remove(q)
candidates = quality[:K-1]
if len(candidates) < K - 1:
break
ans = ratio * (q + sum(candidates))
res = min(res, ans)
return res
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
extra_worker_heap = list()
for i in range(len(quality)):
heappush(extra_worker_heap, (wage[i] / quality[i], quality[i]))
hired_worker_heap = list()
hired_quality = 0
wage_to_quality = 0
min_cost = 1e10
while extra_worker_heap:
cur_wage_to_quality, worker_quality = heappop(extra_worker_heap)
hired_quality += worker_quality
heappush(hired_worker_heap, -worker_quality)
while len(hired_worker_heap) > K:
hired_quality += heappop(hired_worker_heap)
if len(hired_worker_heap) == K:
min_cost = min(min_cost, hired_quality * cur_wage_to_quality)
return min_cost
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
from heapq import *
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
workers = []
for i in range(len(quality)):
workers.append([wage[i] / quality[i], wage[i], quality[i]])
workers = sorted(workers, key = lambda x: [x[0], x[2], x[1]])
cost = math.inf
maxHeap = []
tot = 0
for r, w, q in workers:
heappush(maxHeap, -q)
tot += q
if len(maxHeap) > K:
tot += heappop(maxHeap)
if len(maxHeap) == K:
cost = min(cost, r * tot)
return float(cost)
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution(object):
def mincostToHireWorkers(self, quality, wage, K):
from fractions import Fraction
workers = sorted((w/q, q, w)
for q, w in zip(quality, wage))
print(workers)
ans = float('inf')
pool = []
sumq = 0
for ratio, q, w in workers:
heapq.heappush(pool, -q)
sumq += q
if len(pool) > K:
sumq += heapq.heappop(pool)
if len(pool) == K:
ans = min(ans, ratio * sumq)
return float(ans)
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
import heapq
class Solution:
def mincostToHireWorkers(self, quality, wage, K: int) -> float:
# consider with min coefficient
workers = sorted([[w/q,q,w] for q,w in zip(quality, wage)])
res = float('inf')
pool = []
sumq = 0
for r, q, w in workers:
# candidates with maximaml quality first
heappush(pool, -q)
sumq += q
if len(pool) > K:
# remove redundant
a = heappop(pool)
sumq += a # subtract a from sum
if len(pool) == K:
res = min(res, r * sumq)
return res
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
# sorting workers based on the ration of wage and quality
workers = sorted([float(w) / q, q] for w, q in zip(wage, quality))
ans = float('inf')
heap = []
heapSum = 0
for ratio, q in workers:
heapq.heappush(heap, -q) # max heap based off quality
heapSum += q
if len(heap) > K:# if len of heap > K add largest heap elem
heapSum += heapq.heappop(heap)
if len(heap) == K:
ans = min(ans, ratio * heapSum)
return float(ans)
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
employees = sorted([[w/q, q] for w,q in zip(wage, quality)])
print(employees)
res, totalOut = math.inf, 0
h = []
for rate, output in employees:
totalOut += output
heapq.heappush(h, -output)
if len(h) > K:
totalOut += heapq.heappop(h) #reduce q by removed employee - highest contribution first
if len(h) == K:
res = min(res, totalOut * rate) #worst rate in candidates * output for candidates
return res
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
ratio = sorted((w / q, q) for w, q in zip(wage, quality))
h = []
s, res = 0, float('inf')
for r, q in ratio:
heapq.heappush(h, -q)
s += q
if len(h) > K:
s += heapq.heappop(h)
if len(h) == K:
res = min(res, r * s)
return res
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
import heapq
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
minHeap = []
maxHeap = []
zipped = list(zip(wage, quality))
zipped = sorted(zipped, key = lambda x:x[0]/x[1])
#print(zipped)
minCost = float('inf')
totalQuality = 0
for i in range(len(zipped)):
curRatio = zipped[i][0]/zipped[i][1]
if len(minHeap) < K:
heapq.heappush(minHeap, (-zipped[i][1], zipped[i][0]))
totalQuality += zipped[i][1]
else:
heapq.heappush(maxHeap, (zipped[i][1], zipped[i][0]))
while curRatio*maxHeap[0][0] < curRatio*minHeap[0][0]*-1:
maxTop = heapq.heappop(maxHeap)
minTop = heapq.heappop(minHeap)
heapq.heappush(minHeap, (-maxTop[0], maxTop[1]))
heapq.heappush(maxHeap, (-minTop[0], minTop[1]))
totalQuality = totalQuality + minTop[0]
totalQuality += maxTop[0]
if len(minHeap)== K and totalQuality*curRatio < minCost:
minCost = totalQuality*curRatio
return minCost
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
from heapq import *
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
N = len(quality)
workers = [(wage[i] / float(quality[i]), quality[i]) for i in range(N)]
workers = sorted(workers)
# sum_ = sum([x[1] for x in prices_per_unit[:K - 1]])
# print(prices_per_unit)
result = float('inf')
sum_ = 0
max_heap = []
for i in range(K - 1):
heappush(max_heap, -workers[i][1])
sum_ += workers[i][1]
for i in range(K - 1, len(workers)):
result = min(result, (sum_ + workers[i][1]) * workers[i][0])
if len(max_heap) > 0 and workers[i][1] < -max_heap[0]:
sum_ -= (-heappop(max_heap))
sum_ += workers[i][1]
heappush(max_heap, -workers[i][1])
return result
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
workers = sorted([float(w) / q, q] for w, q in zip(wage, quality))
res = float('inf')
qsum = 0
heap = []
for r, q in workers:
heapq.heappush(heap, -q)
qsum += q
if len(heap) > K: qsum += heapq.heappop(heap)
if len(heap) == K: res = min(res, qsum * r)
return res
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
workers = sorted([(w/q, q) for q, w in zip(quality, wage)])
heap = []
sumq = 0
res = float('inf')
for r, q in workers:
heapq.heappush(heap, -q)
sumq += q
if len(heap)>K:
sumq += heapq.heappop(heap)
if len(heap)==K:
res = min(res, sumq*r)
return res
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
#计算最低工资/工作质量的比值;用一个堆维护K个工作质量最低的工作人员
workers=[]
for q,w in zip(quality,wage):
workers.append((w/q,q,w))
workers.sort()
ans=float('inf')
dui=[]
sumq=0
for ratio,q,w in workers:
#最小堆变为最大堆
heapq.heappush(dui,-q)
sumq+=q
if len(dui)>K:
#去掉一个最高的quality
sumq=sumq+heapq.heappop(dui)
if len(dui)==K:
ans=min(ans,ratio*sumq)
return ans
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
wq = sorted([(a / b, b) for (a, b) in zip(wage, quality)])
res = float('inf')
heap = []
qSum = 0
for avg, q in wq:
qSum += q
heapq.heappush(heap, -q)
if len(heap) > K: qSum += heapq.heappop(heap)
if len(heap) == K: res = min(res, avg * qSum)
return res
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
import heapq
class Solution:
def mincostToHireWorkers_tle(self, quality: List[int], wage: List[int], K: int) -> float:
ans = float('inf')
for i in range(len(quality)):
factor = wage[i] / quality[i]
prices = []
for i in range(len(quality)):
if factor * quality[i] >= wage[i]:
prices.append(factor * quality[i])
if len(prices) < K:
continue
prices.sort()
ans = min(ans, sum(prices[:K]))
return ans
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
if not quality: return 0
workers = sorted([(wage[i] / quality[i], quality[i], wage[i]) for i in range(len(quality))])
min_cost = float('inf')
total = 0
k_workers = []
for w in workers:
total += w[1]
heapq.heappush(k_workers, -w[1])
if len(k_workers) > K:
total += heapq.heappop(k_workers)
if len(k_workers) == K:
min_cost = min(min_cost, total * w[0])
return min_cost
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
import heapq as hq
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
if K == 1:
return min(wage)
N = len(quality)
ratio = [(w / q, i) for i, (w, q) in enumerate(zip(wage, quality))]
ratio.sort()
quality = [quality[i] for _, i in ratio]
ratio = [r for r, _ in ratio]
min_K_queue = [-x for x in quality[: K - 1]]
hq.heapify(min_K_queue)
_sum = sum(quality[: K - 1])
_min = float('inf')
for k in range(K - 1, N):
_min = min((_sum + quality[k]) * ratio[k], _min)
if -quality[k] > min_K_queue[0]:
hq.heappush(min_K_queue, -quality[k])
poped = hq.heappop(min_K_queue)
_sum = _sum + poped + quality[k]
return _min
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
# rate, q, w
q_w = [(w/q,q,w) for q,w in zip(quality,wage)]
q_w.sort()
curr = sum([q_w[i][1] for i in range(K)])
heap = [-q_w[i][1] for i in range(K)]
heapq.heapify(heap)
r = q_w[K-1][0]
res = r*curr
for r,q,w in q_w[K:]:
curr+=q
heapq.heappush(heap,-q)
curr+=heapq.heappop(heap)
res = min(res,curr*r)
return res
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
import heapq as hq
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
if K == 1:
return min(wage)
N = len(quality)
ratio = [(w / q, i) for i, (w, q) in enumerate(zip(wage, quality))]
ratio.sort()
quality = [quality[i] for _, i in ratio]
ratio = [r for r, _ in ratio]
min_K_queue = [-x for x in quality[: K - 1]]
hq.heapify(min_K_queue)
_sum = sum(quality[: K - 1])
_min = float('inf')
for k in range(K - 1, N):
_min = min((_sum + quality[k]) * ratio[k], _min)
if -quality[k] > min_K_queue[0]:
poped = hq.heappop(min_K_queue)
_sum = _sum + poped + quality[k]
hq.heappush(min_K_queue, -quality[k])
return _min
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
import heapq
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
n_workers = len(wage)
pairs = [None]*n_workers # (quality, ratio)
for i in range(n_workers):
pairs[i] = (quality[i], wage[i]/quality[i])
pairs = sorted(pairs, key=lambda x: (x[1])) # sort dec by ratio
# ...incorrect solution...
# max_q = pairs[i:i+K]
# for i in range(n_workers-K+1):
# min_cost = min(min_cost, self.cost(pairs[i:i+K]))
sum_q = sum([p[0] for p in pairs[0:K]])
maxheap_q = [-p[0] for p in pairs[0:K]] # use minus to create max heap
heapq.heapify(maxheap_q)
min_cost = sum_q * pairs[K-1][1]
for i in range(K, n_workers):
sum_q = sum_q - (-heapq.heappop(maxheap_q)) + pairs[i][0]
min_cost = min(min_cost, sum_q * pairs[i][1])
heapq.heappush(maxheap_q, -pairs[i][0]) # push minus value to max heap
return min_cost
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
import heapq as pq
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
ratio = [[y/x, x] for x, y in zip(quality, wage)]
ratio.sort(key = lambda x: x[0])
i = 0
l = []
pq.heapify(l)
r = 1
s = 0
while i < K:
s += ratio[i][1]
pq.heappush(l, -ratio[i][1])
r = ratio[i][0]
i += 1
res = s * r
n = len(quality)
while i < n:
r = ratio[i][0]
num = ratio[i][1]
pq.heappush(l, -num)
val = -pq.heappop(l)
s += (num - val)
res = min(res, s * r)
i += 1
return res
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
workers = sorted([w/q, q] for w, q in zip(wage, quality))
res = float('inf')
qsum = 0
heap = []
for r, q in workers:
heapq.heappush(heap, -q)
qsum += q
if len(heap) > K: qsum += heapq.heappop(heap)
if len(heap) == K: res = min(res, qsum * r)
return res
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
import heapq
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
heap=[]
rate=sorted(((w/q, q) for w, q in zip(wage, quality)))
qsum=0
res=float('inf')
for r, q in rate:
heapq.heappush(heap, -q)
qsum+=q
if len(heap)>K:
qsum+=heapq.heappop(heap)
if len(heap)==K:
res=min(res, r*qsum)
return res
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
A = []
for q,w in zip(quality, wage):
A.append([q, w/q])
pq,ans = [],float('inf')
qSum, ratio = 0,0
for a in sorted(A, key=lambda x:x[1]):
if len(pq) < K:
heapq.heappush(pq, [-a[0], a[1]])
qSum += a[0]
ratio = a[1]
else:
negq = heapq.heappop(pq)[0]
qSum= qSum + negq + a[0]
ratio = a[1]
heapq.heappush(pq, [-a[0], a[1]])
if len(pq) == K:
ans = min(ans, qSum*ratio)
return ans
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
workers=sorted([(w/q, q, w) for w, q in zip(wage, quality)])
print(workers)
result=math.inf
qualitySum = 0
maxheap=[]
for r, q, _ in workers:
heapq.heappush(maxheap,-q)
qualitySum += q
if len(maxheap)>K:
qualitySum+=heapq.heappop(maxheap) #add because its maxheap and we had entered negative, so in theory this line subtracts
if len(maxheap)==K:
print((qualitySum*r,r,qualitySum))
result=min(result,qualitySum*r)
return result
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
n=len(quality)
workers=sorted([w/q,q] for q,w in zip(quality,wage))
que=[]
res=math.inf
curQuality=0
for ratio,q in workers:
heapq.heappush(que,-q)
curQuality+=q
if len(que)>K:
q2=-heapq.heappop(que)
curQuality-=q2
if len(que)==K:
res=min(res,curQuality*ratio)
return res
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
#return self.greedy(quality, wage, K)
return self.heap(quality, wage, K)
def greedy(self, quality, wage, K):
ans = float('inf')
size = len(quality)
for captain in range(size):
ratio = wage[captain] / quality[captain]
prices = []
for worker in range(size):
price = ratio * quality[worker]
if price < wage[worker]:
continue
prices.append(price)
if len(prices) < K:
continue
prices.sort()
ans = min(ans, sum(prices[:K]))
return float(ans)
def heap(self, quality, wage, K):
workers = sorted(( w / q, q, w) for q, w in zip(quality, wage))
ans = float('inf')
myHeap = []
qualitySum = 0
for ratio, q, w in workers:
heapq.heappush(myHeap, -q)
qualitySum += q
if len(myHeap) > K:
qualitySum += heapq.heappop(myHeap)
if len(myHeap) == K:
ans = min(ans, ratio * qualitySum)
return float(ans)
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
import heapq
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
heap=[]
rates=sorted([(w/q, q) for w, q in zip(wage, quality)])
qsum=0
res=float('inf')
for r, q in rates:
heapq.heappush(heap, -q)
qsum+=q
if len(heap)>K:
qsum+=heapq.heappop(heap)
if len(heap)==K:
res=min(res, r*qsum)
return res
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
n = len(quality)
# 1. compute wage per quality for each worker i
wage_per_qual = []
for i in range(n):
wage_per_qual.append(wage[i] / quality[i])
# 2. sort wage per quality (sort worker index)
workers = sorted(list(range(n)), key=lambda i: wage_per_qual[i])
# 3. max heap keep track of minimum k quality
max_heap = []
# current total quality so far
total_quality = 0
min_total = float('inf')
for w in workers:
if len(max_heap) < K:
total_quality += quality[w]
heapq.heappush(max_heap, -quality[w])
if len(max_heap) == K:
min_total = min(min_total, wage_per_qual[w]*total_quality)
else:
if quality[w] < -max_heap[0]:
neg_qual = heapq.heappushpop(max_heap, -quality[w])
total_quality += neg_qual + quality[w]
# # pop the maximum quality to add current worker
# neg_qual = heapq.heappop(max_heap)
# # remove previous max quality
# total_quality += neg_qual
# # add current quality
# total_quality += quality[w]
# heapq.heappush(max_heap, -quality[w])
# use current worker as the base wage
min_total = min(min_total, wage_per_qual[w]*total_quality)
return min_total
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
#Jenny 20201002
#sample 180 ms submission
# 857. Minimum Cost to Hire K Workers
import heapq
class Solution:
# time O(nlogn), space O(n)
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
# 团队开销= 最低效人的 w/q * 团队总 q
# 开除当前团队最低效的人
# 引进待选集合中quality最小的人。
workers = sorted((w/q, w, q) for w, q in zip(wage, quality))
ans = float('inf')
pool = []
sum_q = 0
for (ratio, w, q) in workers:
heapq.heappush(pool, -q)
sum_q += q
if len(pool) > K:
sum_q += heapq.heappop(pool)
if len(pool) == K:
ans = min(ans, ratio * sum_q)
# print(sum_q, ans)
return float(ans)
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
'''
1- expect[i] = wage[i]/quality[i]: meaning i-th worker claims expect[i] money per each unit of its quality. Therefore, if expect[i] > expect[j], that means if we pay j-th worker quality[j]*expect[i] he/she would be more than happy and it's more than its minimal requested wage.
2- Therefore, for k workers sorted by their expect values, if we pay each worker q[i]*expect[k], both rules are satisfied. The total needed money = (sum(q_1 + q_2 + ... + q_k) * expect[k]). Note that this is the minimum money for this k workers, since you have to pay the k-th worker at least q[k]*expect[k]. This part is very tricky, think of this in contrary, if you don't pay each of K workers with expected[k], let's say if you pick expected[k-1], you will not satisfy kth worker. So, the minimum expected pay per quality is expected[k] to satisfy all k workers. Every worker is paid in terms of quality ratio so we come up with a common pay per quality.
3- To recap, we sort workers based on their expect values. Say we are at worker i and want to form a k-group and we already know it would cost sum*expect[i]. To pay the minimum money we should minimize the sum, which can be found using a maxHeap (to replace the max value with a smaller one) to keep the smaller q's as we move forward.
'''
workers = sorted([float(w) / q, q] for w, q in zip(wage, quality))
maxHeap = []
res = float('inf')
qsum = 0
for expect, q in workers:
qsum += q
heapq.heappush(maxHeap, -q)
if len(maxHeap) > K:
qsum += heapq.heappop(maxHeap)
if len(maxHeap) == K:
res = min(res, expect*qsum)
return res
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
import numpy as np
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
workers = sorted([float(w) / q, q] for w, q in zip(wage, quality))
# print(workers)
res = float('inf')
qsum = 0
heap = []
for r, q in workers:
# print(\"*****r: \", r, \"q: \", q)
heapq.heappush(heap, -q)
qsum += q
# print(\"sum:\", qsum)
# print(heap)
if len(heap) > K:
# print(\"popping from heap\")
qsum += heapq.heappop(heap)
# print(\"qsum: \", qsum)
if len(heap) == K:
res = min(res, qsum * r)
# print(\"min: \", res)
return res
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
from heapq import heappush, heappop
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
if len(wage) >= K:
worker = []
for i in range(0, len(quality)):
rate = wage[i] / quality[i]
worker.append((rate, quality[i]))
worker.sort()
base = 0
i = 0
q = []
while i < K-1:
base += worker[i][1]
heappush(q, - worker[i][1])
i += 1
# print(worker)
res = (base + worker[i][1]) * worker[i][0]
while i < len(worker):
# print((worker[i][0], base, res))
rate = worker[i][0]
res = min(res, (base + worker[i][1]) * rate)
heappush(q, - worker[i][1])
base += worker[i][1]
val = heappop(q)
base += val
i += 1
return res
else:
return -1.0
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
# length = len(quality)
# value_orders = sorted(range(length), key=lambda k: wage[k] / quality[k])
# worker_quality = []
# minimum_cost = 0
# for i in range(0, K):
# worker_quality.append(quality[value_orders[i]])
# minimum_cost += wage[value_orders[K - 1]] / quality[value_orders[K - 1]] * quality[value_orders[i]]
# worker_quality.sort()
# for i in range(K, length):
# if quality[value_orders[i]] < worker_quality[-1]:
# worker_quality.pop()
# worker_quality.append(quality[value_orders[i]])
# worker_quality.sort()
# this_round_cost = 0
# for q in worker_quality:
# this_round_cost += q * wage[value_orders[i]] / quality[value_orders[i]]
# minimum_cost = min(minimum_cost, this_round_cost)
# return minimum_cost
workers = [(wage/quality, wage, quality) for wage, quality in zip(wage, quality)]
workers.sort(key=lambda x: x[0])
heap = []
quality_sum = 0
final_cost = float('inf')
for ratio, wage, quality in workers:
heapq.heappush(heap, -1 * quality)
quality_sum += quality
if len(heap) > K:
q = heapq.heappop(heap)
# adding rather than substracting, since quality is inserted as negative
quality_sum += q
if len(heap) == K:
cost = ratio * quality_sum
final_cost = min(final_cost, cost)
return final_cost
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
x = sorted((wage/quality, wage, quality) for wage, quality in zip(wage, quality))
cur_sum = 0
heap = []
res = sys.maxsize
for r, w, q in x:
heapq.heappush(heap, -q)
cur_sum+=q
if len(heap) > K:
cur_sum += heapq.heappop(heap)
if len(heap) == K:
res = min(res, cur_sum*r)
return res
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
from queue import PriorityQueue
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
ratios = [w/q for w, q in zip(wage, quality)]
workers = [(r, q, w) for r, q, w in zip(ratios, quality, wage)]
workers = sorted(workers)
#heap = []
pQueue = PriorityQueue()
min_quality_sum = 0.0
cost = float('inf')
for r, q, w in workers:
pQueue.put(-q)
min_quality_sum = min_quality_sum + q
if pQueue.qsize() > K:
max_quality = pQueue.get()
min_quality_sum = min_quality_sum + max_quality
if pQueue.qsize() == K:
new_cost = r*min_quality_sum
if new_cost < cost:
cost = new_cost
return cost
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
from heapq import *
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
N = len(quality)
workers = [(wage[i] / float(quality[i]), quality[i]) for i in range(N)]
workers = sorted(workers)
# sum_ = sum([x[1] for x in prices_per_unit[:K - 1]])
# print(prices_per_unit)
result = float('inf')
sum_ = 0
max_heap = []
for i in range(K - 1):
heappush(max_heap, -workers[i][1])
sum_ += workers[i][1]
for i in range(K - 1, len(workers)):
result = min(result, (sum_ + workers[i][1]) * workers[i][0])
if len(max_heap) > 0 and workers[i][1] < -max_heap[0]:
sum_ -= (-heappop(max_heap))
sum_ += workers[i][1]
heappush(max_heap, -workers[i][1])
return result
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
from decimal import Decimal
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
workers = [(Decimal(wage[i]/quality[i]), quality[i]) for i in range(len(wage))]
heapq.heapify(workers)
res, unit_price, total_quality, heap = float('inf'), -1.0, 0, []
while workers:
u, q = heapq.heappop(workers)
unit_price = max(u, unit_price)
heapq.heappush(heap, -q)
total_quality += q
# if we already hire K workers, we fire the worker with the highest quality
if len(heap) > K:
total_quality += heapq.heappop(heap)
if len(heap) == K:
res = min(res, total_quality*unit_price)
return res
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
#计算最低工资/工作质量的比值;用一个堆维护K个工作质量最低的工作人员
workers=[]
for q,w in zip(quality,wage):
workers.append((w/q,q,w))
workers.sort()
ans=float('inf')
dui=[]
sumq=0
for ratio,q,w in workers:
#最小堆变为最大堆
heapq.heappush(dui,-q)
sumq+=q
if len(dui)>K:
#去掉一个最高的quality
sumq=sumq+heapq.heappop(dui)
if len(dui)==K:
ans=min(ans,ratio*sumq)
return float(ans)
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
from fractions import Fraction
workers = sorted([(w/q,q,w) for q,w in zip(quality, wage)])
min_cost = float('inf')
from queue import PriorityQueue
pq = PriorityQueue()
summ = 0
print(workers)
for ratio, q, w in workers:
pq.put(-q)
summ += q
if pq.qsize() > K:
summ += pq.get()
if pq.qsize() == K:
min_cost = min(min_cost, ratio*summ)
return float(min_cost)
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
ratios = [(wi/qi, qi) for wi, qi in zip(wage, quality)]
ratios.sort()
res = float('inf')
pq = []
cur = 0
for i, (ratio, q) in enumerate(ratios):
if i >= K - 1:
res = min(res, ratio*(q + cur))
cur += q
heapq.heappush(pq, -q)
if len(pq) > K - 1:
cur += heapq.heappop(pq)
return res
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality, wage, K):
workers = sorted([float(w) / q, q] for w, q in zip(wage, quality))
#print('workers: ',workers)
res = float('inf')
qsum = 0
heap = []
def rec(l,r,heap,newQ):
if l>r:
heap.insert(l,newQ)
return heap
m=l+int((r-l)/2)
if heap[m]>newQ:
return rec(l,m-1,heap,newQ)
else:
return rec(m+1,r,heap,newQ)
for r, q in workers:
#print('before heap: ', heap)
heap=rec(0,len(heap)-1,heap,q)
#print('after heap: ', heap)
qsum += q
if len(heap) > K:
p=heap.pop(K)
#print('heapq.heappop(heap): ',p, 'r:', r, 'qsum: ',qsum)
qsum += -p
if len(heap) == K:
res = min(res, qsum * r)
return res
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality, wage, K):
workers = sorted([float(w) / q, q] for w, q in zip(wage, quality))
print('workers: ',workers)
res = float('inf')
qsum = 0
heap = []
def rec(l,r,heap,newQ):
if l>r:
heap.insert(l,newQ)
return heap
m=l+int((r-l)/2)
if heap[m]>newQ:
return rec(l,m-1,heap,newQ)
else:
return rec(m+1,r,heap,newQ)
for r, q in workers:
#print('before heap: ', heap)
heap=rec(0,len(heap)-1,heap,q)
#print('after heap: ', heap)
qsum += q
if len(heap) > K:
p=heap.pop(-1)
#print('heapq.heappop(heap): ',p, 'r:', r, 'qsum: ',qsum)
qsum += -p
if len(heap) == K:
res = min(res, qsum * r)
return res
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution(object):
def mincostToHireWorkers(self, quality, wage, K):
#from fractions import Fraction
#workers = sorted((Fraction(w, q), q, w)
# for q, w in zip(quality, wage))
workers = sorted((w/q, q, w)
for q, w in zip(quality, wage))
print(workers)
ans = float('inf')
pool = []
sumq = 0
for ratio, q, w in workers:
heapq.heappush(pool, -q)
sumq += q
if len(pool) > K:
sumq += heapq.heappop(pool)
if len(pool) == K:
ans = min(ans, ratio * sumq)
return float(ans)
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality, wage, K):
workers = sorted([float(w) / q, q] for w, q in zip(wage, quality))
#print('workers: ',workers)
res = float('inf')
qsum = 0
heap = []
def rec(l,r,heap,newQ):
if l>r:
heap.insert(l,newQ)
return heap
m=l+int((r-l)/2)
if heap[m]>newQ:
return rec(l,m-1,heap,newQ)
else:
return rec(m+1,r,heap,newQ)
L=0
for r, q in workers:
#print('before heap: ', heap)
heap=rec(0,L-1,heap,q)
L+=1
#print('after heap: ', heap)
qsum += q
if L > K:
p=heap.pop(K)
L-=1
#print('heapq.heappop(heap): ',p, 'r:', r, 'qsum: ',qsum)
qsum += -p
if len(heap) == K:
res = min(res, qsum * r)
return res
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality, wage, K):
workers = sorted([float(w) / q, q] for w, q in zip(wage, quality))
res = float('inf')
qsum = 0
heap = []
def rec(l,r,heap,newQ):
if l>r:
heap.insert(l,newQ)
return heap
m=l+int((r-l)/2)
if heap[m]>newQ:
return rec(l,m-1,heap,newQ)
else:
return rec(m+1,r,heap,newQ)
L=0
for r, q in workers:
heap=rec(0,L-1,heap,q)
L+=1
qsum += q
if L > K:
p=heap.pop(K)
L-=1
qsum += -p
if len(heap) == K:
res = min(res, qsum * r)
return res
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
combine = sorted([(wage[i]/quality[i], quality[i]) for i in range(len(quality))] , key = lambda x: (-x[0], x[1]) )
# qual = [e[1] for e in combine]
# rates = [e[0] for e in combine]
tc = float('inf')
n = len(combine)
q = []
heapq.heapify(q)
for i in range(len(combine)-1,-1,-1):
heapq.heappush(q, -combine[i][1])
if len(q) > K:
heapq.heappop(q)
if i <= n-K:
tc = min(tc, -combine[i][0]*sum(q))
return tc
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
combine = sorted([(wage[i]/quality[i], quality[i]) for i in range(len(quality))] , key = lambda x: (-x[0], x[1]) )
# combine = sorted([(quality[i],wage[i]/quality[i]) for i in range(len(quality))])
qual = [e[1] for e in combine]
rates = [e[0] for e in combine]
tc = float('inf')
n = len(combine)
q = []
heapq.heapify(q)
for i in range(len(combine)-1,-1,-1):
# if i < K-1: return tc
heapq.heappush(q, -qual[i])
if len(q) > K:
heapq.heappop(q)
if i <= n-K:
tc = min(tc, -rates[i]*sum(q))
return tc
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality, wage, K):
workers = sorted([float(w) / q, q] for w, q in zip(wage, quality))
#print('workers: ',workers)
res = float('inf')
qsum = 0
heap = []
def rec(l,r,heap,newQ):
if l>r:
heap.insert(l,newQ)
return heap
m=l+int((r-l)/2)
if heap[m]>newQ:
return rec(l,m-1,heap,newQ)
else:
return rec(m+1,r,heap,newQ)
for r, q in workers:
#print('before heap: ', heap)
heap=rec(0,len(heap)-1,heap,q)
#print('after heap: ', heap)
qsum += q
if len(heap) > K:
p=heap.pop(-1)
#print('heapq.heappop(heap): ',p, 'r:', r, 'qsum: ',qsum)
qsum += -p
if len(heap) == K:
res = min(res, qsum * r)
return res
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
ratios = [(w/q,i) for i,(q,w) in enumerate(zip(quality, wage))]
ratios.sort()
heap = [] # -q
sumq = 0
ans = math.inf
for ratio, i in ratios:
sumq += quality[i]
heapq.heappush(heap, (-quality[i]))
if len(heap) > K:
q = heapq.heappop(heap)
sumq += q # q is negative
if len(heap) == K:
ans = min(ans, sumq*ratio)
return ans
# 7 2.5 6
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
from fractions import Fraction
workers = sorted((Fraction(w, q), q, w) for q, w in zip(quality, wage))
ans = float('inf')
pool = []
sumq = 0
for ratio, q, w in workers:
heapq.heappush(pool, -q)
sumq += q
if len(pool) > K:
sumq += heapq.heappop(pool)
if len(pool) == K:
ans = min(ans, ratio * sumq)
return float(ans)
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution(object):
def mincostToHireWorkers(self, quality, wage, K):
from fractions import Fraction
workers = sorted((Fraction(w, q), q, w)
for q, w in zip(quality, wage))
ans = float('inf')
pool = []
sumq = 0
for ratio, q, w in workers:
heapq.heappush(pool, -q)
sumq += q
if len(pool) > K:
sumq += heapq.heappop(pool)
if len(pool) == K:
ans = min(ans, ratio * sumq)
return float(ans)
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
from heapq import heappush, heappop
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
#store capacity/wage
from fractions import Fraction
cap_wage = sorted((Fraction(w, q), q, w) for q, w in zip(quality, wage))
cap_wage = sorted([(w/c,c,w) for c,w in zip(quality,wage)])
heap = []
re = float('inf')
val=0
for ratio,c,w in cap_wage:
heappush(heap,-c)
val+=c
if len(heap)>K:
val+=heappop(heap)
if len(heap)==K:
re = min(re,val*ratio)
return float(re)
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution(object):
def mincostToHireWorkers(self, quality, wage, K):
from fractions import Fraction
workers = sorted((Fraction(w, q), q, w)
for q, w in zip(quality, wage))
ans = float('inf')
pool = []
sumq = 0
for ratio, q, w in workers:
heapq.heappush(pool, -q)
sumq += q
if len(pool) > K:
sumq += heapq.heappop(pool)
if len(pool) == K:
ans = min(ans, ratio * sumq)
return float(ans)
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution(object):
def mincostToHireWorkers(self, quality, wage, K):
from fractions import Fraction
workers = sorted((Fraction(w, q), q, w)
for q, w in zip(quality, wage))
ans = float('inf')
pool = []
sumq = 0
for ratio, q, w in workers:
heapq.heappush(pool, -q)
sumq += q
if len(pool) > K:
sumq += heapq.heappop(pool)
if len(pool) == K:
ans = min(ans, ratio * sumq)
return float(ans)
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
from fractions import Fraction
workers = sorted((Fraction(w, q), q, w) for q, w in zip(quality, wage))
#print(workers)
min_val = float('Inf')
#print(min_val)
pool = []
sum_q = 0
for r, q, w in workers:
heapq.heappush(pool, -q)
sum_q += q
if len(pool) > K:
sum_q += heapq.heappop(pool)
if len(pool) == K:
min_val = min(min_val, r * sum_q)
return min_val
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution(object):
def mincostToHireWorkers(self, quality, wage, K):
from fractions import Fraction
workers = sorted((Fraction(w, q), q, w)
for q, w in zip(quality, wage))
ans = float('inf')
pool = []
sumq = 0
for ratio, q, w in workers:
heapq.heappush(pool, -q)
sumq += q
if len(pool) > K:
sumq += heapq.heappop(pool)
if len(pool) == K:
ans = min(ans, ratio * sumq)
return float(ans)
# Idea is as follows: If workers are paid in ratio of their qualities, then w_j = (w_ref/q_ref) * q_j
# After paying in the above ratio, to ensure we pay workers their min wage, then we need to select the higher wage/ratio as reference among two possible wage/quality ratios
# So if the size of array is k, then we just select the highest ratio and use that as ref, then
# min cost = (highest ratio ) * (sum of all Qualities)
# or in other words, sort the wage to ratios in increasing order, then last one will be ref ration and this ref ratio times sumq = ans.
# now consider k+1 elements present. then same as above logic, if we sort the wage/quality ratios in increasing order, then any of the ratios from kth to later can be a candidate ref ratio. If k elements, we already know the ans is kth ratio * sumq. Now consider k+1 th element. We can have this as ref ration instead. Then which one would we remove to get k elements? We want to remove the element with highest quality as that would reduce the cost by max. (remember total cost = ref ratio * ( sum of qualities)). So we use max heap to maintain qualities and remove the highest quality when we consider all indexes > k. and among all those possible indexes k to n, we find which gives min cost.
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution(object):
# def mincostToHireWorkers(self, quality, wage, k):
# from fractions import Fraction
# workers = sorted((Fraction(w, q), q, w)
# for q, w in zip(quality, wage))
# maxRatio = workers[-1][0]
# quality.sort()
# sumq=sum(quality[:k])
# return sumq*maxRatio
def mincostToHireWorkers(self, quality, wage, K):
from fractions import Fraction
workers = sorted((Fraction(w, q), q, w)
for q, w in zip(quality, wage))
ans = float('inf')
pool = []
sumq = 0
for ratio, q, w in workers:
heapq.heappush(pool, -q)
sumq += q
if len(pool) > K:
sumq += heapq.heappop(pool)
if len(pool) == K:
ans = min(ans, ratio * sumq)
return float(ans)
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
from heapq import heappush, heappop
from fractions import Fraction
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
workers = [(Fraction(w,q), q, w) for w, q in zip(wage, quality)]
workers.sort()
best = float('inf')
queue = []
sumq = 0
for ratio, q, w in workers:
heappush(queue, -q)
sumq += q
if len(queue) > K:
sumq += heappop(queue)
if len(queue) == K:
best = min(best,ratio * sumq)
return best
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
from fractions import Fraction
workers = sorted((Fraction(w, q), q, w)
for q, w in zip(quality, wage))
ans = float('inf')
pool = []
sumq = 0
for ratio, q, w in workers:
heapq.heappush(pool, -q)
sumq += q
if len(pool) > K:
sumq += heapq.heappop(pool)
if len(pool) == K:
ans = min(ans, ratio * sumq)
return float(ans)
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
from fractions import Fraction
wage_qual = sorted((Fraction(w, q), w, q) for w, q in zip(wage, quality))
candidates = []
psum = 0
ans = float('inf')
for ratio, w, q in wage_qual :
heapq.heappush(candidates, -q)
psum += q
if len(candidates) < K :
continue
elif len(candidates) > K :
psum += heapq.heappop(candidates)
ans = min(ans, psum * ratio)
return ans
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality, wage, K):
workers = sorted([float(w) / q, q] for w, q in zip(wage, quality))
res = float('inf')
qsum = 0
heap = []
for r, q in workers:
heapq.heappush(heap, -q)
qsum += q
if len(heap) > K: qsum += heapq.heappop(heap)
if len(heap) == K: res = min(res, qsum * r)
return res
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
from fractions import Fraction
wage_qual = sorted((Fraction(w, q), w, q) for w, q in zip(wage, quality))
candidates = []
psum = 0
ans = float('inf')
for ratio, w, q in wage_qual :
heapq.heappush(candidates, -q)
psum += q
if len(candidates) > K :
psum += heapq.heappop(candidates)
if len(candidates) == K :
ans = min(ans, psum * ratio)
return ans
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
from fractions import Fraction
workers = sorted((Fraction(w, q), q, w)
for q, w in zip(quality, wage))
ans = float('inf')
pool = []
sumq = 0
for ratio, q, w in workers:
heapq.heappush(pool, -q)
sumq += q
if len(pool) > K:
sumq += heapq.heappop(pool)
if len(pool) == K:
ans = min(ans, ratio * sumq)
return float(ans)
n = len(wage)
if K>n:
return float(0)
re = []
re.append(float('inf'))
self.util(quality,wage,0,[],K,re)
return re[0]
def util(self,q,w,i,p,k,re):
if len(p)==k:
s = sum([t[1] for t in p])
if s<re[0]:
re[0]=s
if i==len(w):
return
self.util(q,w,i+1,[x[:] for x in p],k,re)
if not p:
p.append([q[i],w[i]])
self.util(q,w,i+1,[x[:] for x in p],k,re)
else:
price = (p[0][1]*q[i])/p[0][0]
if price>w[i]:
p.append([q[i],price])
self.util(q,w,i+1,[x[:] for x in p],k,re)
else:
for idx in p:
idx[1] = (w[i]*idx[0])/q[i]
p.append([q[i],w[i]])
self.util(q,w,i+1,[x[:] for x in p],k,re)
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution(object):
def mincostToHireWorkers(self, quality, wage, K):
from fractions import Fraction
workers = sorted((Fraction(w, q), q, w)
for q, w in zip(quality, wage))
ans = float('inf')
pool = []
sumq = 0
for ratio, q, w in workers:
heapq.heappush(pool, -q)
sumq += q
if len(pool) > K:
sumq += heapq.heappop(pool)
if len(pool) == K:
ans = min(ans, ratio * sumq)
return float(ans)
# def mincostToHireWorkers(self, quality, wage, K):
# from fractions import Fraction
# workers = sorted((Fraction(w, q), q, w)
# for q, w in zip(quality, wage))
# ans = float('inf')
# pool = []
# sumq = 0
# for ratio, q, w in workers:
# heapq.heappush(pool, -q)
# sumq += q
# if len(pool) > K:
# sumq += heapq.heappop(pool)
# if len(pool) == K:
# ans = min(ans, ratio * sumq)
# return float(ans)
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
from fractions import Fraction
from heapq import *
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
# quality = [3,1,10,10,1]
# wage = [4,8,2,2,7]
# K = 3
workers = sorted((Fraction(w, q), q, w) for q, w in zip(quality, wage))
# print(workers)
result = float('inf')
maxheap = []
current_sum = 0
for ratio, q, w in workers:
heappush(maxheap, -q)
current_sum += q
if len(maxheap) > K:
current_sum += heappop(maxheap)
if len(maxheap) == K:
result = min(result, ratio * current_sum)
# print(ratio, q, w, maxheap,current_sum,result)
return float(result)
# from fractions import Fraction
# ans = float('inf')
# N = len(quality)
# for captain in range(N):
# # Must pay at least wage[captain] / quality[captain] per qual
# factor = Fraction(wage[captain], quality[captain])
# prices = []
# for worker in range(N):
# price = factor * quality[worker]
# if price >= wage[worker]:
# prices.append(price)
# if len(prices) >= K:
# prices.sort()
# ans = min(ans, sum(prices[:K]))
# return float(ans)
|
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.
|
class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
from fractions import Fraction
# sorting workers based on the ration of wage and quality
workers = sorted((Fraction(w, q), q, w) for q, w in zip(quality, wage))
ans = float('inf')
heap = []
heapSum = 0
for ration, q, w in workers:
heapq.heappush(heap, -q) # max heap based off quality
heapSum += q
if len(heap) > K:# if len of heap > K add largest heap elem
heapSum += heapq.heappop(heap)
if len(heap) == K:
ans = min(ans, ration * heapSum)
return float(ans)
|
Normally, the factorial of a positive integer n is the product of all positive integers less than or equal to n. For example, factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1.
We instead make a clumsy factorial: using the integers in decreasing order, we swap out the multiply operations for a fixed rotation of operations: multiply (*), divide (/), add (+) and subtract (-) in this order.
For example, clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1. However, these operations are still applied using the usual order of operations of arithmetic: we do all multiplication and division steps before any addition or subtraction steps, and multiplication and division steps are processed left to right.
Additionally, the division that we use is floor division such that 10 * 9 / 8 equals 11. This guarantees the result is an integer.
Implement the clumsy function as defined above: given an integer N, it returns the clumsy factorial of N.
Example 1:
Input: 4
Output: 7
Explanation: 7 = 4 * 3 / 2 + 1
Example 2:
Input: 10
Output: 12
Explanation: 12 = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1
Note:
1 <= N <= 10000
-2^31 <= answer <= 2^31 - 1 (The answer is guaranteed to fit within a 32-bit integer.)
|
class Solution:
def clumsy(self, N: int) -> int:
if N <= 2:
return N
if N <= 4:
return N + 3
if (N - 4) % 4 == 0:
return N + 1
elif (N - 4) % 4 <= 2:
return N + 2
else:
return N - 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.