Skip to main content

Command Palette

Search for a command to run...

frog jump

Published
1 min readView as Markdown
class Solution {
    int[] dp;

    public int minimumEnergy(int[] height, int n) {
        dp = new int[n];
        Arrays.fill(dp, -1);
        return helper(n - 1, height);
    }

    private int helper(int i, int[] height) {
        if (i == 0) return 0;  // base case

        if (dp[i] != -1) return dp[i];

        int oneStep = helper(i - 1, height) + Math.abs(height[i] - height[i - 1]);

        int twoStep = Integer.MAX_VALUE;
        if (i > 1)
            twoStep = helper(i - 2, height) + Math.abs(height[i] - height[i - 2]);

        return Math.min(oneStep, twoStep);
    }
}

More from this blog

Amit singh's blog

235 posts