kt: add «1749. Maximum Absolute Sum of Any Subarray»
URL: https://leetcode.com/problems/maximum-absolute-sum-of-any-subarray/ Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
2b57831852
commit
c4a58d7d79
1 changed files with 19 additions and 0 deletions
19
kt/maximum-absolute-sum-of-any-subarray.kt
Normal file
19
kt/maximum-absolute-sum-of-any-subarray.kt
Normal file
|
@ -0,0 +1,19 @@
|
|||
class Solution {
|
||||
private data class Acc(val sum: Int, val min: Int, val max: Int) {
|
||||
val maxAbsoluteSum: Int = max - min
|
||||
|
||||
constructor() : this(0, 0, 0) {}
|
||||
|
||||
fun update(num: Int): Acc =
|
||||
this.copy(
|
||||
sum = sum + num,
|
||||
min = listOf(min, sum + num).min()!!,
|
||||
max = listOf(max, sum + num).max()!!,
|
||||
)
|
||||
}
|
||||
|
||||
fun maxAbsoluteSum(nums: IntArray): Int =
|
||||
nums.fold(Acc()) { acc, it ->
|
||||
acc.update(it)
|
||||
}.maxAbsoluteSum
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue