Open In App

Minimum cost for Hopping Frog to reach stair N

Last Updated : 11 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

There are N stairs, numbered 1,2,…, N. For each i (1≤i≤N), the height of stair i is hi. There is a frog who is initially on stair 1. He will repeat the following action some number of times to reach stair N: If the frog is currently on stair I, jump to Stone i+1 or Stone i+2. Here, a cost of ∣hi −hj∣ is incurred, where j is the stone to land on.

Find the minimum possible total cost incurred before the frog reaches stair N.

Examples:

Input: n = 4, heights = [20, 30, 40, 20]
Output: 20
Explanation: The answer is 20, as the frog may jump from the first stair to the second i.e 1 step (|30-20| – 10 energy lost), and then from the second stair to the last i.e. 2 step (|30-20| = 10 energy lost), given the supplied HEIGHT array of (20,30,40,20). The total amount of energy lost is 20.

Input: n = 5, heights = [30, 20, 50, 10, 40]
Output: 30
Explanation: The answer is 30, as the frog may jump from the first stair to the second i.e. 2 step (|30-50| = 20 energy lost ), and then from the second stair to the last i.e. 2 step (|50-40| = 10 energy lost), given the supplied HEIGHT array of (30, 20, 50, 10, 40). The total amount of energy lost is 30.

Approach 1: Hopping Frog Using Recursion

Start from the n and recursively call the function till 0. The minimum value can be computed using 2 options to perform for the frog i.e bounce 1 step or bounce 2 step.

Follow the steps to Implement the Approach:

  • Make a recursive function
  • Compute for the base case
  • Do the operations for the frog that is bouncing for 1 step or 2 steps i.e left or right (visualize a recursion tree for the call of left and right)
  • Compute the min value from both the operations
  • Return the min of both .

Below is the implementation of above approach:

C++
// c++ program to find min energy exhausted
// to reach the last floor
#include <bits/stdc++.h>
using namespace std;
// Recursive Function to calculate min energy exhausted for
// the frog
int frogenergy(int ind, vector<int>& a)
{
    // Base case = if frog is at last floor, no energy is
    // exhausted
    if (ind == 0)
        return 0;

    // left case = frog bounce 1 floor and energy is
    // exhasted from the previous floor to current fllor
    int left
        = frogenergy(ind - 1, a) + abs(a[ind] - a[ind - 1]);
    // Initialize right to max value because we need to
    // compute min
    int right = INT_MAX;
    // Conditon check if ind >1 because it is not possible
    // to jump 2 floors if floor left is 1 or less
    if (ind > 1)
        // right case = frog bounce 2 floor and energy is
        // also exhaustd from the two floors before the
        // current floor
        right = frogenergy(ind - 2, a)
                + abs(a[ind] - a[ind - 2]);
    // min of the two computed value is the ans.
    return min(left, right);
}

int minBounceEnergy(int n, vector<int>& heights)
{
    // calling the func by passing. reference to index . we
    // put N-1 which it from the last index and floor vector
    return frogenergy(n - 1, heights);
}

// Driver Code
int main()
{
    int n = 4;
    vector<int> heights = { 20, 30, 40, 20 };
    int result = minBounceEnergy(n, heights);
    cout << "Minimum energy exhausted: " << result << endl;
    return 0;
}
// This code is Contributed
// By Shrikant Ramani
C
// c program to find min energy exhausted
// to reach the last floor
#include <stdio.h>
#include <stdlib.h>

// Recursive function to calculate the minimum energy
// exhausted for the frog
int frogEnergy(int ind, int a[], int n)
{
    // Base case: If the frog is at the first floor, no
    // energy is exhausted
    if (ind == 0)
        return 0;

    // Left case: Frog bounces 1 floor, and energy is
    // exhausted from the previous floor to the current
    // floor
    int left = frogEnergy(ind - 1, a, n)
            + abs(a[ind] - a[ind - 1]);

    // Initialize right to a large value because we need to
    // compute the minimum
    int right = 1e9;

    // Condition check if ind > 1 because it's not possible
    // to jump 2 floors if the floor left is 1 or less
    if (ind > 1)
        // Right case: Frog bounces 2 floors, and energy is
        // also exhausted from the two floors before the
        // current floor
        right = frogEnergy(ind - 2, a, n)
                + abs(a[ind] - a[ind - 2]);

    // The minimum of the two computed values is the answer
    return (left < right) ? left : right;
}

// Function to find the minimum energy exhausted for the
// frog to traverse the staircase
int minBounceEnergy(int n, int heights[])
{
    // Calling the function by passing the index (we put
    // n-1, which is from the last index) and the floor
    // array
    return frogEnergy(n - 1, heights, n);
}

// Driver Code
int main()
{
    int n = 4;
    int heights[] = { 20, 30, 40, 20 };
    int result = minBounceEnergy(n, heights);
    printf("Minimum energy exhausted: %d\n", result);
    return 0;
}
Java
// java program to find min energy exhausted
// to reach the last floor
import java.util.*;

public class FrogEnergy {

    // Recursive function to calculate the minimum energy
    // exhausted for the frog
    public static int frogEnergy(int ind,
                                ArrayList<Integer> a)
    {
        // Base case: If the frog is at the last floor, no
        // energy is exhausted
        if (ind == 0)
            return 0;

        // Left case: Frog bounces 1 floor, and energy is
        // exhausted from the previous floor to the current
        // floor
        int left = frogEnergy(ind - 1, a)
                + Math.abs(a.get(ind) - a.get(ind - 1));

        // Initialize right to a large value because we need
        // to compute the minimum
        int right = Integer.MAX_VALUE;

        // Condition check if ind > 1 because it's not
        // possible to jump 2 floors if the floor left is 1
        // or less
        if (ind > 1)
            // Right case: Frog bounces 2 floors, and energy
            // is also exhausted from the two floors before
            // the current floor
            right = frogEnergy(ind - 2, a)
                    + Math.abs(a.get(ind) - a.get(ind - 2));

        // The minimum of the two computed values is the
        // answer
        return Math.min(left, right);
    }

    // Function to find the minimum energy exhausted for the
    // frog to traverse the staircase
    public static int
    minBounceEnergy(int n, ArrayList<Integer> heights)
    {
        // Calling the function by passing a reference to
        // the index (we put n-1, which is from the last
        // index) and the floor list
        return frogEnergy(n - 1, heights);
    }

    // Driver Code
    public static void main(String[] args)
    {
        int n = 4;
        ArrayList<Integer> heights = new ArrayList<>(
            Arrays.asList(20, 30, 40, 20));
        int result = minBounceEnergy(n, heights);
        System.out.println("Minimum energy exhausted: "
                        + result);
    }
}
C#
// C# program for the above approach
using System;

class Program {
    // Recursive Function to calculate min energy exhausted
    // for the frog
    static int FrogEnergy(int ind, int[] a)
    {
        // Base case: if frog is at the first floor, no
        // energy is exhausted
        if (ind == 0)
            return 0;

        // Left case: frog bounces 1 floor and energy is
        // exhausted from the previous floor to the current
        // floor
        int left = FrogEnergy(ind - 1, a)
                + Math.Abs(a[ind] - a[ind - 1]);

        // Initialize right to max value because we need to
        // compute the minimum
        int right = int.MaxValue;

        // Condition check if ind > 1 because it is not
        // possible to jump 2 floors if floor left is 1 or
        // less
        if (ind > 1) {
            // Right case: frog bounces 2 floors and energy
            // is also exhausted from the two floors before
            // the current floor
            right = FrogEnergy(ind - 2, a)
                    + Math.Abs(a[ind] - a[ind - 2]);
        }

        // Minimum of the two computed values is the answer
        return Math.Min(left, right);
    }

    static int MinBounceEnergy(int n, int[] heights)
    {
        // Calling the function by passing reference to
        // index. We put n - 1 to start from the last index
        // and heights array.
        return FrogEnergy(n - 1, heights);
    }

    // Driver Code
    static void Main(string[] args)
    {
        int n = 4;
        int[] heights = { 20, 30, 40, 20 };
        int result = MinBounceEnergy(n, heights);
        Console.WriteLine("Minimum energy exhausted: "
                        + result);
    }
}

// This code is contributed by Susobhan Akhuli
Javascript
// JavaScript program to find min energy exhausted
// to reach the last floor

// Function to calculate min energy exhausted 
// for the frog
function frogenergy(ind, a) {
    // Base case: if frog is at the first floor,
    // no energy is exhausted
    if (ind === 0) {
        return 0;
    }

    // left case: frog bounces 1 floor and energy is 
    // exhausted from the previous floor to the current floor
    let left = frogenergy(ind - 1, a) + Math.abs(a[ind] - a[ind - 1]);
    // Initialize right to Infinity because we
    // need to compute the minimum
    let right = Infinity;
    // Check condition if ind > 1 because it is not possible
    // to jump 2 floors if the floor left is 1 or less
    if (ind > 1) {
        // right case: frog bounces 2 floors and energy is also
        // exhausted from the two floors before the current floor
        right = frogenergy(ind - 2, a) + Math.abs(a[ind] - a[ind - 2]);
    }
    // Minimum of the two computed values is the answer
    return Math.min(left, right);
}

function minBounceEnergy(n, heights) {
    // Calling the function by passing the reference to index. 
    // We put n - 1 which is from the last index and the floor vector
    return frogenergy(n - 1, heights);
}

// Driver Code
const n = 4;
const heights = [20, 30, 40, 20];
const result = minBounceEnergy(n, heights);
console.log("Minimum energy exhausted:", result);
Python3
# Python program to find the minimum energy exhausted
# to reach the last floor

# Recursive function to calculate the minimum energy exhausted for the frog


def frog_energy(ind, a):
    # Base case: If the frog is at the last floor, no energy is exhausted
    if ind == 0:
        return 0

    # Left case: Frog bounces 1 floor, and energy is exhausted from the previous floor to the current floor
    left = frog_energy(ind - 1, a) + abs(a[ind] - a[ind - 1])

    # Initialize right to a large value because we need to compute the minimum
    right = float('inf')

    # Condition check if ind > 1 because it's not possible to jump 2 floors if the floor left is 1 or less
    if ind > 1:
        # Right case: Frog bounces 2 floors, and energy is also exhausted from the two floors before the current floor
        right = frog_energy(ind - 2, a) + abs(a[ind] - a[ind - 2])

    # The minimum of the two computed values is the answer
    return min(left, right)

# Function to find the minimum energy exhausted for the frog to traverse the staircase


def minBounceEnergy(n, heights):
    # Calling the function by passing a reference to the index (we put n-1, which is from the last index) and the floor list
    return frog_energy(n - 1, heights)


# Driver Code
if __name__ == "__main__":
    n = 4
    heights = [20, 30, 40, 20]
    result = minBounceEnergy(n, heights)
    print("Minimum energy exhausted:", result)

Output
Minimum energy exhausted: 20









Time Complexity – O(2^n). The time complexity of the code is exponential in worst case due to exponential growth in recursive function calls.

Space Complexity – O(n) as it is determined the maximum dept of recursion stack, where n is number of floors.

Approach 2: Hopping Frog Using Dynamic Programming( memoization):

We can observe this problem has overlapping sub problems. In order to apply memoization to improve this code, you would add an array or vector to store and reuse the outcomes of the subproblems.

Memoization helps us optimise the code because it eliminates unnecessary calculations.

For example : When computing frogEnergy(3, heights), for instance, the subproblem of computing frogEnergy(2, heights) arises. Memoization ensures that the result of frogEnergy(2, heights) is utilised when computing frogEnergy(3, heights) rather than being recomputated.

Below Steps to implement Memoization

  • To store computed results, create a data structure (such as an array or vector).
  • Check to see if the outcome of the current input has already been saved in the data structure before conducting a calculation.
  • Return the result if it is found; if not, compute it and save it in the data structure.
  • When the same subproblem arises, use the previously stored results to avoid performing further calculations.
C++
// c++ program to find min energy exhausted
// to reach the last floor
#include <bits/stdc++.h>
using namespace std;
// Recursive Function to calculate min energy exhausted for
// the frog
int f(int ind, vector<int>& a, vector<int>& dp)
{
    // Base case = if frog is at last floor, no energy is
    // exhausted
    if (ind == 0)
        return 0;

    // if the value where dp[ind] is standing and is not
    // equal to -1 means we have calculated it in some other
    // previous recursion call and we do not need to
    // calculate again instead we just can return the value
    // stored
    if (dp[ind] != -1)
        return dp[ind];

    // left case = frog bounce 1 floor and energy is
    // exhasted from the previous floor to current fllor
    int left = f(ind - 1, a, dp) + abs(a[ind] - a[ind - 1]);
    // Initialize right to max value because we need to
    // compute min
    int right = INT_MAX;
    // Conditon check if ind >1 because it is not possible
    // to jump 2 floors if floor left is 1 or less
    if (ind > 1)
        // right case = frog bounce 2 floor and energy is
        // also exhaustd from the two floors before the
        // current floor
        right
            = f(ind - 2, a, dp) + abs(a[ind] - a[ind - 2]);
    // min of the two computed value is the ans.
    dp[ind] = min(left, right);

    return dp[ind];
}

int minBounceEnergy(int n, vector<int>& energy_costs)
{
    // creating a 1D vecctor dp and initializing with -1
    vector<int> dp(n, -1);
    // calling the func by passing. reference to index . we
    // put N-1 which it from the last index and floor vector
    return f(n - 1, energy_costs, dp);
}

// Driver Code
int main()
{
    int n = 4;
    vector<int> energy_costs = { 20, 30, 40, 20 };
    int result = minBounceEnergy(n, energy_costs);
    cout << "Minimum energy exhausted: " << result << endl;
    return 0;
}
// This code is Contributed
// By Shrikant Ramani
Java
import java.util.Arrays;

public class FrogJump {
    // Recursive Function to calculate min energy exhausted
    // for the frog
    static int frogEnergy(int ind, int[] a, int[] dp)
    {
        // Base case: If frog is at the last floor, no
        // energy is exhausted
        if (ind == 0)
            return 0;

        // If the value where dp[ind] is standing is not
        // equal to -1, it means we have calculated it in
        // some other previous recursion call, and we do not
        // need to calculate it again; instead, we can
        // return the stored value.
        if (dp[ind] != -1)
            return dp[ind];

        // Left case: Frog bounces 1 floor, and energy is
        // exhausted from the previous floor to the current
        // floor
        int left = frogEnergy(ind - 1, a, dp)
                + Math.abs(a[ind] - a[ind - 1]);

        // Initialize right to a large value because we need
        // to compute min
        int right = Integer.MAX_VALUE;

        // Condition check if ind > 1 because it is not
        // possible to jump 2 floors if the floor left is 1
        // or less
        if (ind > 1)
            // Right case: Frog bounces 2 floors, and energy
            // is also exhausted from the two floors before
            // the current floor
            right = frogEnergy(ind - 2, a, dp)
                    + Math.abs(a[ind] - a[ind - 2]);

        // Min of the two computed values is the answer, and
        // we store it in dp[ind] for future use.
        dp[ind] = Math.min(left, right);

        return dp[ind];
    }

    // Function to find the minimum energy exhausted for the
    // frog to traverse the staircase
    static int frogJump(int n, int[] heights)
    {
        // Creating an array dp and initializing it with -1
        int[] dp = new int[n];
        Arrays.fill(dp, -1);
        // Calling the function by passing a reference to
        // the index (we put n-1, which is from the last
        // index) and the floor array
        return frogEnergy(n - 1, heights, dp);
    }

    // Driver Code
    public static void main(String[] args)
    {
        int n = 4;
        int[] heights = { 20, 30, 40, 20 };
        int result = frogJump(n, heights);
        System.out.println("Minimum energy exhausted: "
                        + result);
    }
}
C#
using System;
using System.Collections.Generic;

class Program
{
    static int MinBounceEnergy(int n, List<int> energyCosts)
    {
        List<int> dp = new List<int>(new int[n]);
        for (int i = 0; i < n; i++)
        {
            dp[i] = -1;
        }
        return F(n - 1, energyCosts, dp);
    }

    static int F(int ind, List<int> a, List<int> dp)
    {
        if (ind == 0)
            return 0;

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

        int left = F(ind - 1, a, dp) + Math.Abs(a[ind] - a[ind - 1]);

        int right = int.MaxValue;

        if (ind > 1)
        {
            right = F(ind - 2, a, dp) + Math.Abs(a[ind] - a[ind - 2]);
        }

        dp[ind] = Math.Min(left, right);

        return dp[ind];
    }

    static void Main()
    {
        int n = 4;
        List<int> energyCosts = new List<int> { 20, 30, 40, 20 };
        int result = MinBounceEnergy(n, energyCosts);
        Console.WriteLine("Minimum energy exhausted: " + result);
    }
}
Javascript
function minBounceEnergy(n, energyCosts) {
    let dp = new Array(n).fill(-1);
    return F(n - 1, energyCosts, dp);
}

function F(ind, a, dp) {
    if (ind === 0)
        return 0;

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

    let left = F(ind - 1, a, dp) + Math.abs(a[ind] - a[ind - 1]);

    let right = Number.MAX_SAFE_INTEGER;

    if (ind > 1) {
        right = F(ind - 2, a, dp) + Math.abs(a[ind] - a[ind - 2]);
    }

    dp[ind] = Math.min(left, right);

    return dp[ind];
}

// Main function equivalent
function main() {
    let n = 4;
    let energyCosts = [20, 30, 40, 20];
    let result = minBounceEnergy(n, energyCosts);
    console.log("Minimum energy exhausted: " + result);
}

// Invoke the main function
main();
Python3
# Python program to find min energy exhausted
# to reach the last floor

# Recursive Function to calculate min energy exhausted for the frog


def frog_energy(ind, a, dp):
    # Base case: If frog is at the last floor, no energy is exhausted
    if ind == 0:
        return 0

    # If the value where dp[ind] is standing is not equal to -1,
    # it means we have calculated it in some other previous recursion call,
    # and we do not need to calculate it again; instead, we can return the stored value.
    if dp[ind] != -1:
        return dp[ind]

    # Left case: Frog bounces 1 floor, and energy is exhausted from the previous floor to the current floor
    left = frog_energy(ind - 1, a, dp) + abs(a[ind] - a[ind - 1])

    # Initialize right to a large value because we need to compute min
    right = float('inf')

    # Condition check if ind > 1 because it is not possible to jump 2 floors if the floor left is 1 or less
    if ind > 1:
        # Right case: Frog bounces 2 floors, and energy is also exhausted from the two floors before the current floor
        right = frog_energy(ind - 2, a, dp) + abs(a[ind] - a[ind - 2])

    # Min of the two computed values is the answer, and we store it in dp[ind] for future use.
    dp[ind] = min(left, right)

    return dp[ind]


def frog_bounce(n, floor):
    # Creating a 1D list dp and initializing it with -1
    dp = [-1] * n
    # Calling the function by passing a reference to the index (we put n-1, which is from the last index) and the floor list
    return frog_energy(n - 1, floor, dp)


# Driver Code
n = 4
floor = [20, 30, 40, 20]
result = frog_bounce(n, floor)
print("Minimum energy exhausted:", result)

Output
Minimum energy exhausted: 20






Time Complexity – O(n). The code iterates through the stairs once, and for each stair, it performs a constant amount of work, resulting in a linear time complexity.

Space Complexity – O(n). The code for dynamic programming stores computed results in an array dp of size n, adding to the space complexity.

Approach 3: Hopping Frog Using Dynamic Programming( Tabulation):

  • Create a 1D array called dp and set its initial value to 0 for the simplest scenario in order to store the minimal energy for each stair.
  • From the second stair through the last one, calculate and store the absolute minimum energy required.
  • Think of two scenarios for each stair: bouncing from the stair before it or, if possible, bouncing from two staircases before.
  • The bare minimum energy needed for each stair is updated in the dp array.
  • The value at the bottom step in the dp array denotes the minimal amount of energy required to ascend to the top floor.
C++
// c++ program to find min energy exhausted
// to reach the last floor
#include <bits/stdc++.h>
using namespace std;
// Recursive Function to calculate min energy exhausted for
// the frog
int f(int ind, vector<int>& a, vector<int>& dp)
{
    // Base case = if frog is at last floor, no energy is
    // exhausted
    if (ind == 0)
        return 0;

    // if the value where dp[ind] is standing and is not
    // equal to -1 means we have calculated it in some other
    // previous recursion call and we do not need to
    // calculate again instead we just can return the value
    // stored
    if (dp[ind] != -1)
        return dp[ind];

    // left case = frog bounce 1 floor and energy is
    // exhasted from the previous floor to current fllor
    int left = f(ind - 1, a, dp) + abs(a[ind] - a[ind - 1]);
    // Initialize right to max value because we need to
    // compute min
    int right = INT_MAX;
    // Conditon check if ind >1 because it is not possible
    // to jump 2 floors if floor left is 1 or less
    if (ind > 1)
        // right case = frog bounce 2 floor and energy is
        // also exhaustd from the two floors before the
        // current floor
        right
            = f(ind - 2, a, dp) + abs(a[ind] - a[ind - 2]);
    // min of the two computed value is the ans.
    dp[ind] = min(left, right);

    return dp[ind];
}

int minBounceEnergy(int n, vector<int>& energy_costs)
{
    // creating a 1D vecctor dp and initializing with -1
    vector<int> dp(n, -1);
    // calling the func by passing. reference to index . we
    // put N-1 which it from the last index and floor vector
    return f(n - 1, energy_costs, dp);
}

// Driver Code
int main()
{
    int n = 4;
    vector<int> energy_costs = { 20, 30, 40, 20 };
    int result = minBounceEnergy(n, energy_costs);
    cout << "Minimum energy exhausted: " << result << endl;
    return 0;
}
// This code is Contributed
// By Shrikant Ramani
Java
public class FrogJump {
    // Function to find the minimum energy exhausted for the
    // frog to traverse the staircase
    static int frogBounce(int n, int[] heights)
    {
        // Creating an array dp and initializing it with 0
        int[] dp = new int[n];

        // Base case
        dp[0] = 0;

        // For loop starting from 1 as the base case is
        // already computed earlier
        for (int i = 1; i < n; i++) {
            // Calculation for left case i.e., 1 bounce
            int left
                = dp[i - 1]
                + Math.abs(heights[i] - heights[i - 1]);
            int right = Integer.MAX_VALUE;

            // Calculation for right case i.e., 2 bounces
            if (i > 1) {
                right = dp[i - 2]
                        + Math.abs(heights[i]
                                - heights[i - 2]);
            }

            // Compute min
            dp[i] = Math.min(left, right);
        }

        return dp[n - 1];
    }

    // Driver Code
    public static void main(String[] args)
    {
        int n = 4;
        int[] heights = { 20, 30, 40, 20 };
        int result = frogBounce(n, heights);
        System.out.println("Minimum energy exhausted: "
                        + result);
    }
}
C#
using System;
using System.Collections.Generic;

class Program
{
    static int MinBounceEnergy(int n, List<int> heights)
    {
        // Creating a 1D array dp and initializing with -1
        int[] dp = new int[n];
        // Base case
        dp[0] = 0;

        // For loop starting from 1 as base case is already computed earlier
        for (int i = 1; i < n; i++)
        {
            // Calculation for left case i.e., 1 bounce
            int left = dp[i - 1] + Math.Abs(heights[i] - heights[i - 1]);
            int right = int.MaxValue;

            // Calculation for left case i.e., 2 bounce
            if (i > 1)
                right = dp[i - 2] + Math.Abs(heights[i] - heights[i - 2]);

            // Compute min
            dp[i] = Math.Min(left, right);
        }

        return dp[n - 1];
    }

    // Driver Code
    static void Main(string[] args)
    {
        int n = 4;
        List<int> heights = new List<int> { 20, 30, 40, 20 };
        int result = MinBounceEnergy(n, heights);
        Console.WriteLine("Minimum energy exhausted: " + result);
    }
}
Javascript
// Function to find the minimum energy exhausted for the frog to traverse the staircase
function frogBounce(n, heights) {
    // Creating an array dp and initializing it with 0
    let dp = new Array(n).fill(0);

    // Base case
    dp[0] = 0;

    // For loop starting from 1 as the base case is already computed earlier
    for (let i = 1; i < n; i++) {
        // Calculation for left case i.e., 1 bounce
        let left = dp[i - 1] + Math.abs(heights[i] - heights[i - 1]);
        let right = Infinity;

        // Calculation for right case i.e., 2 bounces
        if (i > 1) {
            right = dp[i - 2] + Math.abs(heights[i] - heights[i - 2]);
        }

        // Compute min
        dp[i] = Math.min(left, right);
    }

    return dp[n - 1];
}

// Driver Code
function main() {
    let n = 4;
    let heights = [20, 30, 40, 20];
    let result = frogBounce(n, heights);
    console.log("Minimum energy exhausted: " + result);
}

// Calling the main function to execute the code
main();
Python3
def frog_bounce(n, heights):
    # Creating a 1D list dp and initializing it with 0
    dp = [0] * n

    # Base case
    dp[0] = 0

    # For loop starting from 1 as the base case is already computed earlier
    for i in range(1, n):
        # Calculation for left case i.e., 1 bounce
        left = dp[i - 1] + abs(heights[i] - heights[i - 1])
        right = float('inf')

        # Calculation for right case i.e., 2 bounces
        if i > 1:
            right = dp[i - 2] + abs(heights[i] - heights[i - 2])

        # Compute min
        dp[i] = min(left, right)

    return dp[n - 1]


# Driver Code
n = 4
heights = [20, 30, 40, 20]
result = frog_bounce(n, heights)
print("Minimum energy exhausted:", result)

Output
Minimum energy exhausted: 20






Time Complexity : O(n), where n is the number of stairs in the staircase.

Space Complexity : O(n), as the space is used for the dp array to store computed results for each stair.

Approach 4: Hopping Frog Using Dynamic Programming( Space Optimization):

Only previous two values are needed to compute the result for current state.

Set the variables prior and prev2 to their respective initial values for the current and previous minimum energies.

  • Calculate the least amount of energy required for each set of stairs while taking 1- and 2-bounce alternatives into account, then update prev and prev2 accordingly.
  • Returning to the previous floor signifies using the least amount of energy to get there.
C++
// c++ program to find min energy exhausted
// to reach the last floor
#include <bits/stdc++.h>
using namespace std;

int minBounceEnergy(int n, vector<int>& heights)
{
    // creating a 1D vecctor dp and initializing with -1
    vector<int> dp(n, 0);
    // base case
    dp[0] = 0;

    // for loop staring from 1 as base case is already
    // computed earlier
    for (int i = 1; i < n; i++) {
        // calculation for left case i.e 1 bounce
        int left
            = dp[i - 1] + abs(heights[i] - heights[i - 1]);
        int right = INT_MAX;

        // calculation for left case i.e 2 bounce
        if (i > 1)
            right = dp[i - 2]
                    + abs(heights[i] - heights[i - 2]);
        // compute min
        dp[i] = min(left, right);
    }

    return dp[n - 1];
}

// Driver Code
int main()
{
    int n = 4;
    vector<int> heights = { 20, 30, 40, 20 };
    int result = minBounceEnergy(n, heights);
    cout << "Minimum energy exhausted: " << result << endl;
    return 0;
}
// This code is Contributed
// By Shrikant Ramani
Java
public class FrogJump {
    // Function to find the minimum energy exhausted for the
    // frog to traverse the staircase
    static int frogBounce(int n, int[] heights)
    {
        int prev = 0; // Initialize prev variable
        int prev2 = 0; // Initialize prev2 variable

        // For loop starting from 1 as base case is already
        // computed earlier
        for (int i = 1; i < n; i++) {
            // Calculation for left case i.e., 1 bounce
            int left
                = prev
                + Math.abs(heights[i] - heights[i - 1]);
            int right = Integer.MAX_VALUE;

            // Calculation for right case i.e., 2 bounces
            if (i > 1) {
                right = prev2
                        + Math.abs(heights[i]
                                - heights[i - 2]);
            }

            // Compute min and store it in curr
            int curr = Math.min(left, right);

            // Update prev and prev2 for the next iteration
            prev2 = prev;
            prev = curr;
        }

        // Return prev as the function call was from
        // dp[i-1], i.e., it represents the minimum energy
        // exhausted
        return prev;
    }

    // Driver Code
    public static void main(String[] args)
    {
        int n = 4;
        int[] heights = { 20, 30, 40, 20 };
        int result = frogBounce(n, heights);
        System.out.println("Minimum energy exhausted: "
                        + result);
    }
}
C#
using System;
using System.Collections.Generic;

class Program
{
    static int MinBounceEnergy(int n, List<int> heights)
    {
        // Creating a 1D array dp and initializing with -1
        int[] dp = new int[n];
        // Base case
        dp[0] = 0;

        // For loop starting from 1 as the base case is already computed earlier
        for (int i = 1; i < n; i++)
        {
            // Calculation for left case i.e., 1 bounce
            int left = dp[i - 1] + Math.Abs(heights[i] - heights[i - 1]);
            int right = int.MaxValue;

            // Calculation for left case i.e., 2 bounce
            if (i > 1)
                right = dp[i - 2] + Math.Abs(heights[i] - heights[i - 2]);

            // Compute min
            dp[i] = Math.Min(left, right);
        }

        return dp[n - 1];
    }

    static void Main(string[] args)
    {
        int n = 4;
        List<int> heights = new List<int> { 20, 30, 40, 20 };
        int result = MinBounceEnergy(n, heights);
        Console.WriteLine("Minimum energy exhausted: " + result);
    }
}
//This code is contributed by Kishan.
Javascript
function minBounceEnergy(n, heights) {
    // creating an array dp and initializing with 0
    let dp = new Array(n).fill(0);
    // base case
    dp[0] = 0;

    // for loop starting from 1 as base case is already computed earlier
    for (let i = 1; i < n; i++) {
        // calculation for left case i.e., 1 bounce
        let left = dp[i - 1] + Math.abs(heights[i] - heights[i - 1]);
        let right = Infinity;

        // calculation for left case i.e., 2 bounce
        if (i > 1)
            right = dp[i - 2] + Math.abs(heights[i] - heights[i - 2]);
        
        // compute min
        dp[i] = Math.min(left, right);
    }

    return dp[n - 1];
}

// Driver Code
let n = 4;
let heights = [20, 30, 40, 20];
let result = minBounceEnergy(n, heights);
console.log("Minimum energy exhausted: " + result);
Python3
def frog_bounce(n, heights):
    prev = 0 # Initialize prev variable
    prev2 = 0 # Initialize prev2 variable

    # For loop starting from 1 as base case is already computed earlier
    for i in range(1, n):
        # Calculation for left case i.e., 1 bounce
        left = prev + abs(heights[i] - heights[i - 1])
        right = float('inf')

        # Calculation for right case i.e., 2 bounces
        if i > 1:
            right = prev2 + abs(heights[i] - heights[i - 2])

        # Compute min and store it in curr
        curr = min(left, right)

        # Update prev and prev2 for the next iteration
        prev2 = prev
        prev = curr

    # Return prev as the function call was from dp[i-1], i.e., it represents the minimum energy exhausted
    return prev


# Driver Code
n = 4
heights = [20, 30, 40, 20]
result = frog_bounce(n, heights)
print("Minimum energy exhausted:", result)

Output
Minimum energy exhausted: 20






Time Complexity : O(n), where n is the number of stairs in the staircase.

Space Complexity : O(1), as the code uses only a constant amount of extra space for the prev and prev2 variables, regardless of the input size.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads