Skip to content

Commit 7104cfd

Browse files
authored
Create maximum-number-of-ones.py
1 parent 9b72113 commit 7104cfd

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

Python/maximum-number-of-ones.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# Time: O(1)
2+
# Space: O(1)
3+
4+
class Solution(object):
5+
def maximumNumberOfOnes(self, width, height, sideLength, maxOnes):
6+
"""
7+
:type width: int
8+
:type height: int
9+
:type sideLength: int
10+
:type maxOnes: int
11+
:rtype: int
12+
"""
13+
if width < height:
14+
width, height = height, width
15+
16+
# 1. split matrix by SxS tiles
17+
# 2. split each SxS tile into four parts
18+
# (r, c), (r, S-c), (S-r, c), (S-r, S-c)
19+
# 3. for each count of tile part in matrix is
20+
# (R+1)*(C+1), (R+1)*C, R*(C+1), R*C (already in descending order)
21+
# 4. fill one into matrix by tile part of which count is in descending order
22+
# until number of ones in a tile comes to maxOnes
23+
#
24+
# ps. area of a tile and its count in matrix are as follows:
25+
#
26+
# |<---- c ---->|<-- S-c -->|
27+
# ^ | |
28+
# | | |
29+
# r (R+1)*(C+1) | (R+1)*C |
30+
# | | |
31+
# v | |
32+
# ---------------------------
33+
# ^ | |
34+
# | | |
35+
# S-r R*(C+1) | R*C |
36+
# | | |
37+
# v | |
38+
# ---------------------------
39+
#
40+
41+
R, r = divmod(height, sideLength)
42+
C, c = divmod(width, sideLength)
43+
assert(R <= C)
44+
area_counts = [(r*c, (R+1)*(C+1)), \
45+
(r*(sideLength-c), (R+1)*C), \
46+
((sideLength-r)*c, R*(C+1)), \
47+
((sideLength-r)*(sideLength-c), R*C)]
48+
result = 0
49+
for area, count in area_counts:
50+
area = min(maxOnes, area)
51+
result += count*area
52+
maxOnes -= area
53+
if not maxOnes:
54+
break
55+
return result

0 commit comments

Comments
 (0)