問題: 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