861. Score After Flipping Matrix

406 篇文章 0 订阅
406 篇文章 0 订阅

1,题目要求
We have a two dimensional matrix A where each value is 0 or 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.
这里写图片描述
对于一个由0和1构成的矩阵,对于每一行和每一列都可以进行翻转——即0变成1,1变成0;求翻转结果的最大值。

2,题目思路
对于这一题,首先,对于这个矩阵每一行的第一个数字,当它为1时,一定是最大的,即:
1000 > 0111。
其次,再遍历这个矩阵除了第一列之外的所有列。
因为我们一定要将A[i][0]置位1,因此对于每一列中的A[i][j],如果它的值等于A[i][0],则说明它可以置位1,也就说说可以置位1的个数多了一个。
但是,这样的置换并不能保证所得的结果一定是最大的,因此要看如果这样翻转后,得到的1是不是最多的,如果是最多的,则计算这样的1所构成的二进制数的最大值。否则,就按照原先的1的形式计算(翻转两次即可)。

3,程序源码

class Solution {
public:
    int matrixScore(vector<vector<int>>& A) {   //对行和列进行flip,其中A是M*N的矩阵(flip:1->0, 0->1)
        int M = A.size(), N = A[0].size();
        int res = (1<<(N-1)) * M;     //每一行的一个元素都应该被翻转为1,这样的到的数字才是最大的
        for(int j = 1;j < N;j++)
        {
            int tmp = 0;//每一列中,在flip后可以得到的1的个数
            for(int i = 0;i < M;i++)
            {
                if(A[i][j] == A[i][0])
                    tmp++;
            }
            int max_1 = max(M-tmp, tmp);//即翻转后的1的个数多,还是再翻转一次变为原样的1的个数多。
            cout<<max_1<<endl;
            res += max_1 * (1<<(N-1-j));
        }
        return res;
    }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值