# 10.10.2025 [3147. Taking Maximum Energy From the Mystic Dungeon]
Max k-distant suffix sum #medium #array
10.10.2025
3147. Taking Maximum Energy From the Mystic Dungeon medium blog post substack youtube
Join me on Telegram
Problem TLDR
Max k-distant suffix sum #medium #array
Intuition
Each
ksums have stable positions. Trackksums, drop if negative.
Approach
can be done in-place
Complexity
Time complexity: $$O(n)$$
Space complexity: $$O(n)$$ or O(1) with input mutation
Code
// 724ms
fun maximumEnergy(e: IntArray, k: Int) = (e.size-1 downTo 0)
.maxOf { e[it] += if (it+k < e.size) e[it+k] else 0; e[it] }
// 21ms
pub fn maximum_energy(mut e: Vec<i32>, k: i32) -> i32 {
let k = k as usize; for i in k..e.len() { e[i%k] = e[i] + 0.max(e[i%k]) }
*e[..k].iter().max().unwrap()
}


