Maximum Number of Ones — LeetCode 1183 Python Solution

HardLeetCode PremiumGreedyMathSortingHeap (Priority Queue)
Problem
#1183
Reading time
2 min

The problem

Consider a matrix M with dimensions width * height, such that every cell has value 0 or 1, and any square sub-matrix of M of size sideLength * sideLength has at most maxOnes ones. Return the maximum possible number of ones that the matrix M can have.

Example

Input
width = 3, height = 3, sideLength = 2, maxOnes = 1
Output
4
Explanation
In a 3*3 matrix, no 2*2 sub-matrix can have more than 1 one.

Python solution

Python
class Solution:
    def maximumNumberOfOnes(
        self, width: int, height: int, sideLength: int, maxOnes: int
    ) -> int:
        x = sideLength
        cnt = [0] * (x * x)
        for i in range(width):
            for j in range(height):
                k = (i % x) * x + (j % x)
                cnt[k] += 1
        cnt.sort(reverse=True)
        return sum(cnt[:maxOnes])

Complexity

MeasureComplexity
TimeO(m \times n), where m and n are the number of rows and columns of the matrix, respectively
SpaceO(1) to O(n) auxiliary

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 1183. Maximum Number of Ones is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.

The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1183. Maximum Number of Ones?
LeetCode 1183. Maximum Number of Ones is rated Hard on LeetCode.
What topics does LeetCode 1183. Maximum Number of Ones cover?
LeetCode 1183. Maximum Number of Ones is tagged Greedy, Math, Sorting and Heap (Priority Queue) on LeetCode.
Is LeetCode 1183. Maximum Number of Ones a premium problem?
Yes. LeetCode 1183. Maximum Number of Ones is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview