Skip to content

Instantly share code, notes, and snippets.

@frol
Last active February 28, 2019 22:18
Show Gist options
  • Select an option

  • Save frol/2b5cbc243fc0125f2716cbb41e61b912 to your computer and use it in GitHub Desktop.

Select an option

Save frol/2b5cbc243fc0125f2716cbb41e61b912 to your computer and use it in GitHub Desktop.
// Simple
fun arrayManipulation(n: Int, queries: Array<Array<Int>>): Long {
val checkpoints = Array<Long>(n, { 0 })
for ((start, end, value) in queries) {
checkpoints[start - 1] += value.toLong()
if (end < n) {
checkpoints[end] -= value.toLong()
}
}
var accumulated_sum: Long = 0;
var max: Long = 0;
for (checkpoint in checkpoints) {
accumulated_sum += checkpoint
if (accumulated_sum > max) {
max = accumulated_sum
}
}
return max
}
// Overkill
data class CheckpointFold(var max_value: Long, var accumulated_value: Long)
operator fun CheckpointFold.plusAssign(value: Long) {
this.accumulated_value += value
if (this.max_value < this.accumulated_value) {
this.max_value = this.accumulated_value
}
}
// Complete the arrayManipulation function below.
fun arrayManipulation(n: Int, queries: Array<Array<Int>>): Long {
val checkpoints = Array<Long>(n, { 0 })
for ((start, end, value) in queries) {
checkpoints[start - 1] += value.toLong()
if (end < n) {
checkpoints[end] -= value.toLong()
}
}
return checkpoints.fold(
CheckpointFold(0, 0),
{ checkpoint_fold, checkpoint ->
checkpoint_fold += checkpoint
checkpoint_fold
}
).max_value
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment