LeetCode Entry

3147. Taking Maximum Energy From the Mystic Dungeon

10.10.2025 medium 2025 kotlin rust

Max k-distant suffix sum

3147. Taking Maximum Energy From the Mystic Dungeon medium blog post substack youtube

6c72b184-248f-4f18-8f48-de7d078824ff (1).webp

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/1138

Problem TLDR

Max k-distant suffix sum #medium #array

Intuition

Each k sums have stable positions. Track k sums, 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()
    }