Skip to content

Commit 9b72113

Browse files
authored
Create maximum-number-of-ones.cpp
1 parent 26f1d04 commit 9b72113

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

C++/maximum-number-of-ones.cpp

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Time: O(1)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int maximumNumberOfOnes(int width, int height, int sideLength, int maxOnes) {
7+
if (width < height) {
8+
swap(width, height);
9+
}
10+
11+
int R = height / sideLength, r = height % sideLength;
12+
int C = width / sideLength, c = width % sideLength;
13+
assert(R <= C);
14+
vector<pair<int, int>> area_counts = {{r * c, (R + 1) * (C + 1)},
15+
{r * (sideLength - c), (R + 1) * C},
16+
{(sideLength - r) * c, R * (C + 1)},
17+
{(sideLength - r) * (sideLength - c), R * C}};
18+
int result = 0;
19+
for (const auto& [area, count] : area_counts) {
20+
result += count * min(maxOnes, area);
21+
maxOnes -= min(maxOnes, area);
22+
if (!maxOnes) {
23+
break;
24+
}
25+
}
26+
return result;
27+
}
28+
};

0 commit comments

Comments
 (0)