Sponsored
Sponsored
To maximize the score, we should ensure that the leftmost bit (most significant bit) of each binary number (row) is 1. If the first bit of any row is 0, we can flip that entire row.
Once the leading bits are all 1, we maximize further by toggling columns where the count of 0s is more than 1s. This ensures that the binary numbers are as large as possible.
Time Complexity: O(m * n), where m is the number of rows and n is the number of columns in the grid. Space Complexity: O(1), using inplace modifications.
1var matrixScore = function(grid) {
2 const m = grid.length;
3 const n = grid[0].length;
4
5 for (let i = 0; i < m; i++) {
6 if (grid[i][0] === 0) {
7 for (let j = 0; j < n; j++) {
8 grid[i][j] ^= 1;
9 }
10 }
11 }
12
13 let score = 0;
14 for (let j = 0; j < n; j++) {
15 let colCount = 0;
16 for (let i = 0; i < m; i++) {
17 if (grid[i][j] === 1) {
18 colCount++;
19 }
20 }
21 colCount = Math.max(colCount, m - colCount);
22 score += colCount * (1 << (n - j - 1));
23 }
24
25 return score;
26};
JavaScript handles the task using similar logic to ensure maximum binary score by flipping the rows at the initial stage and optimizing 0s and 1s counts thereafter.
This approach differs slightly by treating the majority of 1s per column as more influential. Instead of flipping rows first, the solution primarily ensures maximal 1 presence per column, beginning with the columns themselves.
Time Complexity: O(m * n), as each element in the matrix grid is visited once. Space Complexity: O(1), operating in-place.
1
In Python, the algorithm immediately accounts for the most significant bit interactions and adjusts subsequent digits based on perception and binary values.