Skip to content

Commit 09f377e

Browse files
authored
Create maximum-value-sum-by-placing-three-rooks-ii.py
1 parent 6bbf49a commit 09f377e

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Time: O(m * n * logk + nCr((k-1)*(2*k-1)+1), 3) * k) = O(m * n)
2+
# Space: O(k * (m + n)) = O(m + n)
3+
4+
import heapq
5+
import itertools
6+
7+
8+
# heap, brute force
9+
class Solution(object):
10+
def maximumValueSum(self, board):
11+
"""
12+
:type board: List[List[int]]
13+
:rtype: int
14+
"""
15+
k = 3
16+
min_heaps = [[] for _ in xrange(len(board[0]))]
17+
for i in xrange(len(board)):
18+
min_heap = []
19+
for j in xrange(len(board[0])):
20+
heapq.heappush(min_heap, (board[i][j], i, j))
21+
if len(min_heap) == k+1:
22+
heapq.heappop(min_heap)
23+
for v, i, j in min_heap:
24+
heapq.heappush(min_heaps[j], (v, i, j))
25+
if len(min_heaps[j]) == k+1:
26+
heapq.heappop(min_heaps[j])
27+
min_heap = []
28+
for h in min_heaps:
29+
for x in h:
30+
heapq.heappush(min_heap, x)
31+
if len(min_heap) == ((k-1)*(2*k-1)+1)+1: # each choice excludes at most 2k-1 candidates, we should have at least (k-1)*(2k-1)+1 candidates
32+
heapq.heappop(min_heap)
33+
return max(x[0]+y[0]+z[0] for x, y, z in itertools.combinations(min_heap, k) if all(len({x[i], y[i], z[i]}) == k for i in xrange(1, 2+1)))

0 commit comments

Comments
 (0)