861 Score After Flipping Matrix

178 篇文章 0 订阅
160 篇文章 0 订阅

1 题目

We have a two dimensional matrix A where each value is 0or 1.

A move consists of choosing any row or column, and toggling each value in that row or column: changing all 0s to 1s, and all 1s to 0s.

After making any number of moves, every row of this matrix is interpreted as a binary number, and the score of the matrix is the sum of these numbers.

Return the highest possible score.

Example 1:

Input: [[0,0,1,1],[1,0,1,0],[1,1,0,0]]
Output: 39
Explanation:
Toggled to [[1,1,1,1],[1,0,0,1],[1,1,1,1]].
0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39

Note:

  1. 1 <= A.length <= 20
  2. 1 <= A[0].length <= 20
  3. A[i][j] is 0 or 1.

2 尝试解

2.1 分析

给定一个由0和1组成的矩阵,可以对某一行或某一列进行异或操作。如果每一行代表一个二进制的整数,求任意操作后,可以得到的所有数之和最大值。

行操作会改变最高位的数字,所以只能用于首位为0的行。先通过行操作,将第一列数字全变为1,那么只要不改变第一列,所有的行操作都只会使和减小,那么只有列操作可行。从第2列开始,如果该列中0比1多,则对该列使用列操作。最后求和即可。

2.2 代码

class Solution {
public:
    int matrixScore(vector<vector<int>>& A) {
        int result = 0;
        for(int i = 0; i < A.size(); i++){
            if(!A[i][0]){
                for(int j = 0; j < A[i].size();j++){
                    A[i][j] = 1 - A[i][j];
                }
            }
        }
        result = A.size();
        for(int i = 1; i < A[0].size(); i++){
            int count = 0;
            for(int j = 0; j < A.size(); j++){
                if(A[j][i])
                    count++;
            }
            result = 2*result + (2*count<A.size()?A.size()-count:count);
        }
        return result;
    }
};

3 标准解

class Solution {
public:
    int matrixScore(vector<vector<int>> A) {
        int M = A.size(), N = A[0].size(), res = (1 << (N - 1)) * M;
        for (int j = 1; j < N; j++) {
            int cur = 0;
            for (int i = 0; i < M; i++) cur += A[i][j] == A[i][0];
            res += max(cur, M - cur) * (1 << (N - j - 1));
        }
        return res;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值