Untitled

mail@pastecode.io avatar
unknown
kotlin
21 days ago
926 B
3
Indexable
Never
fun matrixScore(matrix: Array<IntArray>): Int {
    val rows = matrix.size
    val cols = matrix[0].size

    // firstly we should maximize number via matrix[y][0] = 1
    for (y in 0 until rows) {
        if (matrix[y][0] == 0) {
            for (x in 0 until cols) {
                matrix[y][x] = 1 - matrix[y][x]
            }
        }
    }

    // secondly we should maximize ones in each column
    for (x in 1 until cols) {
        var oneCnt = 0
        for (y in 0 until rows) {
            oneCnt += matrix[y][x]
        }
        if (oneCnt < (rows + 1) / 2) {
            for (y in 0 until rows) {
                matrix[y][x] = 1 - matrix[y][x]
            }
        }
    }

    var sum = 0
    for (y in 0 until rows) {
        var num = 0
        for (x in 0 until cols) {
            num += Math.pow(2.0, (cols - x - 1).toDouble()).toInt() * matrix[y][x]
        }
        sum += num
    }

    return sum
}
Leave a Comment