Leet Code Daily 2024-05-13 - Score After Flipping Matrix
Solution
Enumerate possible states of toggling columns and for each case, decide the best result per row.
Code
class Solution {
public:
int matrixScore(vector<vector<int>>& grid) {
int n = grid.size(), m = grid[0].size();
vector<int> vals;
for (int i = 0; i < n; i++) {
int val = 0;
for (int j = 0; j < m; j++) {
val = (val << 1) + grid[i][j];
}
vals.push_back(val);
cout << val << endl;
}
int ans = INT_MIN, ones = ((1 << m) - 1);
for (int mask = 0; mask <= ones; mask++) {
int sum = 0;
for (const auto& val : vals) {
sum += max(val ^ mask, val ^ mask ^ ones);
}
ans = max(ans, sum);
}
return ans;
}
};