diff --git a/kt/maximum-matrix-sum.kt b/kt/maximum-matrix-sum.kt new file mode 100644 index 0000000..272e2ce --- /dev/null +++ b/kt/maximum-matrix-sum.kt @@ -0,0 +1,30 @@ +class Solution { + fun abs(x: Int): Int = listOf(x, -x).max() + + private data class Accumulator(val sum: Long, val negatives: Int, val minimumAbs: Int) { + fun update(x: Int): Accumulator = + Accumulator( + sum + abs(x), + negatives + + if (x < 0) { + 1 + } else { + 0 + }, + listOf(minimumAbs, abs(x)).min(), + ) + + fun adjust(): Accumulator = + when { + negatives % 2 != 0 -> Accumulator(sum - 2 * minimumAbs, negatives, minimumAbs) + else -> this + } + } + + fun maxMatrixSum(matrix: Array): Long = + matrix.fold(Accumulator(0L, 0, Int.MAX_VALUE)) { acc, row -> + row.fold(acc) { acc, it -> + acc.update(it) + } + }.adjust().sum +}