问题: 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.
方法: 使最终结果最大一共需要做两部操作: 1)遍历所有行的第一个元素,如果为0则反转该行,保证每个二进制数的最高位都为1 2)遍历所有列(不包含首列,因为首列为最高位),如果该列0的个数多于一半则反转该列 经过如上两部操作之后则矩阵的结果即为最大
具体实现:
import kotlin.math.absclass ScoreAfterFlippingMatrix { fun matrixScore(A: Array): Int { for (i in A.indices) { if (A[i][0] == 0) { for (j in A[0].indices) { A[i][j] = abs(A[i][j] - 1) } } } for (j in 1..A[0].lastIndex) { var zeroNum = 0 for (i in A.indices) { if (A[i][j] == 0) { zeroNum++ } } if (zeroNum * 2 > A.size) { for (i in A.indices) { A[i][j] = abs(A[i][j] - 1) } } } var sum = 0 for (i in A.indices) { for (j in A[0].indices) { sum += A[i][j] shl (A[0].lastIndex - j) } } return sum }}fun main(args: Array ) { val array = arrayOf(intArrayOf(0, 0, 1, 1), intArrayOf(1,0 ,1, 0), intArrayOf(1, 1, 0, 0))// val array = arrayOf(intArrayOf(0, 1), intArrayOf(1,1)) val scoreAfterFlippingMatrix = ScoreAfterFlippingMatrix() val result = scoreAfterFlippingMatrix.matrixScore(array) print("result: $result")}复制代码
有问题随时沟通