|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# 1727. Largest Submatrix With Rearrangements |
| 4 | +# Medium |
| 5 | +# https://leetcode.com/problems/largest-submatrix-with-rearrangements |
| 6 | + |
| 7 | +=begin |
| 8 | +You are given a binary matrix matrix of size m x n, and you are allowed to rearrange the columns of the matrix in any order. |
| 9 | +Return the area of the largest submatrix within matrix where every element of the submatrix is 1 after reordering the columns optimally. |
| 10 | +
|
| 11 | +Example 1: |
| 12 | +Input: matrix = [[0,0,1],[1,1,1],[1,0,1]] |
| 13 | +Output: 4 |
| 14 | +Explanation: You can rearrange the columns as shown above. |
| 15 | +The largest submatrix of 1s, in bold, has an area of 4. |
| 16 | +
|
| 17 | +Example 2: |
| 18 | +Input: matrix = [[1,0,1,0,1]] |
| 19 | +Output: 3 |
| 20 | +Explanation: You can rearrange the columns as shown above. |
| 21 | +The largest submatrix of 1s, in bold, has an area of 3. |
| 22 | +
|
| 23 | +Example 3: |
| 24 | +Input: matrix = [[1,1,0],[1,0,1]] |
| 25 | +Output: 2 |
| 26 | +Explanation: Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2. |
| 27 | +
|
| 28 | +Constraints: |
| 29 | +m == matrix.length |
| 30 | +n == matrix[i].length |
| 31 | +1 <= m * n <= 105 |
| 32 | +matrix[i][j] is either 0 or 1. |
| 33 | +=end |
| 34 | + |
| 35 | +# @param {Integer[][]} matrix |
| 36 | +# @return {Integer} |
| 37 | +def largest_submatrix(matrix) |
| 38 | + m = matrix.size |
| 39 | + n = matrix[0].size |
| 40 | + columns = Array.new(m) { [] } |
| 41 | + |
| 42 | + 0.upto(n - 1) do |j| |
| 43 | + seq = 0 |
| 44 | + |
| 45 | + (m - 1).downto(0) do |i| |
| 46 | + if matrix[i][j] == 1 |
| 47 | + seq += 1 |
| 48 | + columns[i][j] = seq |
| 49 | + else |
| 50 | + seq = 0 |
| 51 | + end |
| 52 | + end |
| 53 | + end |
| 54 | + |
| 55 | + max = 0 |
| 56 | + |
| 57 | + 0.upto(m - 1) do |i| |
| 58 | + cols = columns[i].compact.sort |
| 59 | + n = cols.size |
| 60 | + (n - 1).downto(0) do |j| |
| 61 | + max = [max, (n - j) * cols[j]].max |
| 62 | + end |
| 63 | + end |
| 64 | + |
| 65 | + max |
| 66 | +end |
| 67 | + |
| 68 | +# **************** # |
| 69 | +# TEST # |
| 70 | +# **************** # |
| 71 | + |
| 72 | +require "test/unit" |
| 73 | +class Test_largest_submatrix < Test::Unit::TestCase |
| 74 | + def test_ |
| 75 | + assert_equal 4, largest_submatrix([[0, 0, 1], [1, 1, 1], [1, 0, 1]]) |
| 76 | + assert_equal 3, largest_submatrix([[1, 0, 1, 0, 1]]) |
| 77 | + assert_equal 2, largest_submatrix([[1, 1, 0], [1, 0, 1]]) |
| 78 | + end |
| 79 | +end |
0 commit comments