kt: add «1975. Maximum Matrix Sum»

URL:	https://leetcode.com/problems/maximum-matrix-sum/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-11-24 22:19:59 +01:00
parent da9d7ea742
commit 6e55e96ef0
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

30
kt/maximum-matrix-sum.kt Normal file
View file

@ -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<IntArray>): Long =
matrix.fold(Accumulator(0L, 0, Int.MAX_VALUE)) { acc, row ->
row.fold(acc) { acc, it ->
acc.update(it)
}
}.adjust().sum
}