Leetcode 861. Score after flipping a matrix

Source: Internet
Author: User

There is a two-dimensional matrix A where each element has a value of 0 or 1 .

Move refers to selecting any row or column and converting each value in that row or column: Change all 0 1 to, change all to 1 0 .

After making any number of moves, each row of the matrix is interpreted as a binary number, and the Matrix's score is the sum of those numbers.

Returns the highest possible score.

Example:

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

A simple greedy strategy. Make sure that each row starts with 0, and then make sure that each column is as much as 1.

classSolution { Public:    intMatrixscore (vector<vector<int>>&A) {if(a.size () = =0|| a[0].size () = =0) {            return 0; }        introw = A.size (), column = a[0].size (), sum =0;  for(inti =0; i < row; i++) {            if(a[i][0] ==0) {                 for(intj =0; J < column; J + +) {A[i][j]=1-A[i][j]; }            }        }         for(intj =0; J < column; J + +) {            intZero =0, one =0;  for(inti =0; i < row; i++) {                if(A[i][j] = =0) {Zero++; } Else{ One++; }            }            if(Zero >One ) {                 for(inti =0; i < row; i++) {A[i][j]=1-A[i][j]; }            }        }         for(inti =0; i < row; i++) {             for(intj =0; J < column; J + +) {sum+ = a[i][j] * POW (2, Column-j-1); }        }        returnsum; }};

Leetcode 861. Score after flipping a matrix

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.