问题: 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.git
方法: 使最终结果最大一共须要作两部操做: 1)遍历全部行的第一个元素,若是为0则反转该行,保证每一个二进制数的最高位都为1 2)遍历全部列(不包含首列,由于首列为最高位),若是该列0的个数多于一半则反转该列 通过如上两部操做以后则矩阵的结果即为最大github
具体实现:bash
import kotlin.math.abs
class ScoreAfterFlippingMatrix {
fun matrixScore(A: Array<IntArray>): 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<String>) {
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")
}
复制代码
有问题随时沟通ui
具体代码实现能够参考Githubthis