Open In App

Program for Bridge and Torch problem

Last Updated : 15 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array times[] of positive distinct integers denoting the crossing time of n people. These people are standing on one side of the bridge. There is only one torch with them and the bridge cannot be crossed without the torch. The bridge can hold at max two people at a time. When two people cross the bridge, they must move at the slower person's pace. Find the minimum total time in which all persons can cross the bridge. See the Torch and Bridge puzzle to know more.
Note: Slower person space is given by larger time. 

Examples:

Input: times[] = [10, 20, 30]
Output: 60
Explanation: Total time incurred in whole journey will be 20 + 10 + 30 = 60
1. Firstly person '1' and '2' cross the bridge with total time about 20 min(maximum of 10, 20)
2. Now the person '1' will come back with total time of '10' minutes.
3. Lastly the person '1' and '3' cross the bridge with total time about 30 minutes

Input: times = [1, 2, 5, 8}
Output: 15
Explanation: See Torch and Bridge puzzle for full explanation.

Using Recursion - O(2^n) Time and O(n) Space

For the recursive approach, there are two cases to consider:

Case 1: The two fastest people cross first, then the fastest one returns with the torch, allowing the two slowest to cross. Finally, the second fastest returns. This total time is given by:

  • option1 = times[1] + times[0] + times[n - 1] + times[1].

Case 2: The two slowest people cross first, with the second fastest then returning. This allows the next two slowest to cross. This total time is given by:

  • option2 = times[n - 1] + times[0] + times[n - 2] + times[0].

Base Cases:

  • If only one person is left (n == 1), the minimum time is just the time of that person crossing alone, which is times[0].
  • If there are two people (n == 2), the minimum time required is the time taken by the second person to cross with the first, which is times[1].
  • For three people (n == 3), they all cross with the minimum time being times[0] + times[1] + times[2].

Mathematically, the recurrence relation looks like:

  • minCrossingTime(times, n) = min(option1 + minCrossingTime(times, n - 2), option2 + minCrossingTime(times, n - 2))
C++
// C++ code for Bridge and Torch
// using recursion
#include <bits/stdc++.h>
using namespace std;

// Recursive function to calculate
// minimum crossing time
int minCrossingTime(vector<int>& times, int n) {
  
    // Base cases
    if (n == 1) return times[0];
    if (n == 2) return times[1];
    if (n == 3) return times[0] + times[1] + times[2];

    // Case 1: Send two fastest people first 
    // and the fastest one returns
    int option1 = times[1] + times[0] 
                    + times[n - 1] + times[1];

    // Case 2: Send two slowest people first 
    // and the second fastest returns
    int option2 = times[n - 1] + times[0] 
                     + times[n - 2] + times[0];

    // Recur for the remaining people after either case
    return min(option1 + minCrossingTime(times, n - 2),
               option2 + minCrossingTime(times, n - 2));
}

int bridgeAndTorch(vector<int>&times) {
  
   sort(times.begin(), times.end());
  
   return minCrossingTime(times, times.size()); 
}


int main() {
  
    vector<int> times = {10, 20, 30};
  
    cout << bridgeAndTorch(times);
    return 0;
}
Java
// Java code for Bridge and Torch
// using recursion
import java.util.*;

class GfG {

    // Recursive function to calculate
    // minimum crossing time
    static int minCrossingTime(ArrayList<Integer> times, int n) {
  
        // Base cases
        if (n == 1) return times.get(0);
        if (n == 2) return times.get(1);
        if (n == 3) return times.get(0) 
                  + times.get(1) + times.get(2);

        // Case 1: Send two fastest people first 
        // and the fastest one returns
        int option1 = times.get(1) + times.get(0) 
                        + times.get(n - 1) + times.get(1);

        // Case 2: Send two slowest people first 
        // and the second fastest returns
        int option2 = times.get(n - 1) + times.get(0) 
                         + times.get(n - 2) + times.get(0);

        // Recur for the remaining people after either case
        return Math.min(option1 + minCrossingTime(times, n - 2),
                         option2 + minCrossingTime(times, n - 2));
    }

    static int bridgeAndTorch(ArrayList<Integer> times) {
  
        Collections.sort(times);
  
        return minCrossingTime(times, times.size()); 
    }

    public static void main(String[] args) {
  
        ArrayList<Integer> times 
          = new ArrayList<>(Arrays.asList(10, 20, 30));
  
        System.out.println(bridgeAndTorch(times));
    }
}
Python
# Python code for Bridge and Torch
# using recursion

def minCrossingTime(times, n):
  
    # Base cases
    if n == 1:
        return times[0]
    if n == 2:
        return times[1]
    if n == 3:
        return times[0] + times[1] + times[2]

    # Case 1: Send two fastest people first 
    # and the fastest one returns
    option1 = times[1] + times[0] + times[n - 1] + times[1]

    # Case 2: Send two slowest people first 
    # and the second fastest returns
    option2 = times[n - 1] + times[0] + times[n - 2] + times[0]

    # Recur for the remaining people after either case
    return min(option1 + minCrossingTime(times, n - 2),
               option2 + minCrossingTime(times, n - 2))

def bridgeAndTorch(times):
    times.sort() 
    return minCrossingTime(times, len(times))

if __name__ == "__main__":
    times = [10, 20, 30]  
    print(bridgeAndTorch(times))
C#
// C# code for Bridge and Torch
// using recursionusing System;
using System;
using System.Collections.Generic;

class GfG {
  
    // Recursive function to calculate 
    // minimum crossing time
    static int MinCrossingTime(List<int> times, int n) {
      
        // Base cases
        if (n == 1) return times[0];
        if (n == 2) return times[1];
        if (n == 3) return times[0]
                      + times[1] + times[2];

        // Case 1: Send two fastest people first 
        // and the fastest one returns
        int option1 = times[1] + times[0] 
                      + times[n - 1] + times[1];

        // Case 2: Send two slowest people first 
        // and the second fastest returns
        int option2 = times[n - 1] + times[0]
                        + times[n - 2] + times[0];

        // Recur for the remaining people after either case
        return Math.Min(option1 + MinCrossingTime(times, n - 2),
                        option2 + MinCrossingTime(times, n - 2));
    }

    // Method to solve the bridge and torch problem
    static int BridgeAndTorch(List<int> times) {
        times.Sort();  
        return MinCrossingTime(times, times.Count);
    }

    static void Main() {
        List<int> times
          = new List<int> { 10, 20, 30 };
        Console.WriteLine(BridgeAndTorch(times));
    }
}
JavaScript
// Javascript code for Bridge and Torch
// using recursion

// Recursive function to calculate 
// minimum crossing time
function minCrossingTime(times, n) {

    // Base cases
    if (n === 1) return times[0];
    if (n === 2) return times[1];
    if (n === 3) return times[0] + times[1] + times[2];

    // Case 1: Send two fastest people first 
    // and the fastest one returns
    let option1 = times[1] + times[0] + times[n - 1] + times[1];

    // Case 2: Send two slowest people first 
    // and the second fastest returns
    let option2 = times[n - 1] + times[0] + times[n - 2] + times[0];

    // Recur for the remaining people after either case
    return Math.min(option1 + minCrossingTime(times, n - 2),
                    option2 + minCrossingTime(times, n - 2));
}

// Function to solve the bridge and torch problem
function bridgeAndTorch(times) {
    times.sort((a, b) => a - b); 
    return minCrossingTime(times, times.length);
}

const times = [10, 20, 30];
console.log(bridgeAndTorch(times));  

Output
60

Using Top-Down DP (Memoization) - O(nlogn) Time and O(n) Space

If we notice carefully, we can observe that the above recursive solution holds the following two properties of Dynamic Programming.

1. Optimal Substructure:

The problem can be broken down into smaller subproblems where the minimum crossing time for n people depends on the optimal crossing time for n-2 people (as we're either sending two people first and having one return, or sending two slowest and having one return).

2. Overlapping Subproblems:

The crossing time for a group of size n depends on the crossing times of smaller groups, specifically for n-2, meaning we calculate the same values multiple times. Hence, we use memoization to store results for subproblems and reuse them.

  • We initialize the memo array of size n + 1 to store the minimum crossing time for each subproblem (number of people left to cross). All values are initially set to -1.
  • If memo[n] is -1, we calculate it recursively, using the two options described above, and store the result in memo[n].
C++
// C++ code for Bridge and Torch problem
// using Memoization
#include <bits/stdc++.h>
using namespace std;

// Recursive function to calculate minimum
// crossing time with memoization
int minCrossingTime(vector<int>& times, 
                    int n, vector<int>& memo) {

    // Base cases
    if (n == 1) return times[0];
    if (n == 2) return times[1];
    if (n == 3) return times[0] + times[1] + times[2];
  
    // Check if result for this subproblem is
 	 // already computed
    if (memo[n] != -1) return memo[n];

    // Case 1: Send two fastest people first
    // and the fastest one returns
    int option1 = times[1] + times[0] 
                          + times[n - 1] + times[1];

    // Case 2: Send two slowest people first and 
    // the second fastest returns
    int option2 = times[n - 1] + times[0] 
                            + times[n - 2] + times[0];

    // Recur for the remaining people after either case
    int result = min(option1 + minCrossingTime(times, n - 2, memo),
                 option2 + minCrossingTime(times, n - 2, memo));

    // Store result in memoization vector
    memo[n] = result;
    return result;
}

int bridgeAndTorch(vector<int>& times) {
  
    sort(times.begin(), times.end());
    int n = times.size();
  
     // Vector to store results for memoization
    vector<int> memo(n + 1, -1); 
    return minCrossingTime(times, n, memo);
}

int main() {
    vector<int> times = {10, 20, 30};
    cout << bridgeAndTorch(times);
    return 0;
}
Java
// Java code for Bridge and Torch problem
// using Memoization
import java.util.ArrayList;
import java.util.Collections;

class GfG {

    // Recursive function to calculate minimum
    // crossing time with memoization
    static int minCrossingTime(ArrayList<Integer> times, 
                             int n, ArrayList<Integer> memo) {
        
        // Base cases
        if (n == 1) return times.get(0);
        if (n == 2) return times.get(1);
        if (n == 3) return times.get(0) + times.get(1) + times.get(2);

        // Check if result for this subproblem is 
      	// already computed
        if (memo.get(n) != -1) return memo.get(n);

        // Case 1: Send two fastest people first
        // and the fastest one returns
        int option1 = times.get(1) + times.get(0) 
                    + times.get(n - 1) + times.get(1);

        // Case 2: Send two slowest people first 
        // and the second fastest returns
        int option2 = times.get(n - 1) + times.get(0) 
                      + times.get(n - 2) + times.get(0);

        // Recur for the remaining people after either case
        int result = Math.min(option1 + minCrossingTime(times, n - 2, memo),
                              option2 + minCrossingTime(times, n - 2, memo));

        // Store result in memoization list
        memo.set(n, result);
        return result;
    }

    static int bridgeAndTorch(ArrayList<Integer> times) {

        // Sort the times list
        Collections.sort(times);
        int n = times.size();

        // List to store results for memoization
        ArrayList<Integer> memo 
         = new ArrayList<>(Collections.nCopies(n + 1, -1));
      
        return minCrossingTime(times, n, memo);
    }

    public static void main(String[] args) {
      
        ArrayList<Integer> times = new ArrayList<>();
        times.add(10);
        times.add(20);
        times.add(30);
        
        System.out.println(bridgeAndTorch(times));  
    }
}
Python
# Python code for Bridge and Torch problem
# using Memoization

def min_crossing_time(times, n, memo):
  
    # Base cases
    if n == 1:
        return times[0]
    if n == 2:
        return times[1]
    if n == 3:
        return times[0] + times[1] + times[2]

    # Check if result for this subproblem
    # is already computed
    if memo[n] != -1:
        return memo[n]

    # Case 1: Send two fastest people first
    # and the fastest one returns
    option1 = times[1] + times[0] + times[n - 1] + times[1]

    # Case 2: Send two slowest people first
    # and the second fastest returns
    option2 = times[n - 1] + times[0] + times[n - 2] + times[0]

    # Recur for the remaining people after either case
    result = min(option1 + min_crossing_time(times, n - 2, memo),
                 option2 + min_crossing_time(times, n - 2, memo))

    # Store result in memoization list
    memo[n] = result
    return result

def bridge_and_torch(times):
    times.sort()
    n = len(times)

    # List to store results for memoization,
    # initialized to -1
    memo = [-1] * (n + 1)
    
    return min_crossing_time(times, n, memo) 
  
if __name__ == "__main__":
    times = [10, 20, 30]
    print(bridge_and_torch(times)) 
C#
// C# code for Bridge and Torch problem
// using Memoization
using System;
using System.Collections.Generic;

class GfG {

    // Recursive function to calculate minimum
    // crossing time with memoization
    static int MinCrossingTime(List<int> times, 
                                   int n, List<int> memo) {
        
        // Base cases
        if (n == 1) return times[0];
        if (n == 2) return times[1];
        if (n == 3) return times[0] + times[1] + times[2];

        // Check if result for this subproblem is already computed
        if (memo[n] != -1) return memo[n];

        // Case 1: Send two fastest people first
        // and the fastest one returns
        int option1 = times[1] + times[0] + times[n - 1] + times[1];

        // Case 2: Send two slowest people first
        // and the second fastest returns
        int option2 = times[n - 1] + times[0] + times[n - 2] + times[0];

        // Recur for the remaining people after either case
        int result = Math.Min(option1 + MinCrossingTime(times, n - 2, memo),
                              option2 + MinCrossingTime(times, n - 2, memo));

        // Store result in memoization list
        memo[n] = result;
        return result;
    }

    static int BridgeAndTorch(List<int> times) {

        // Sort the times list
        times.Sort();
        int n = times.Count;

        // List to store results for memoization
        List<int> memo = new List<int>(new int[n + 1]);
        for (int i = 0; i <= n; i++) memo[i] = -1;

        return MinCrossingTime(times, n, memo);
    }

    static void Main(string[] args) {
        List<int> times = new List<int> {10, 20, 30};
        
        Console.WriteLine(BridgeAndTorch(times)); 
    }
}
JavaScript
// JavaScript code for Bridge and Torch
// problem using Memoization

function minCrossingTime(times, n, memo) {

    // Base cases
    if (n === 1) return times[0];
    if (n === 2) return times[1];
    if (n === 3) return times[0] + times[1] + times[2];

    // Check if result for this subproblem 
    // is already computed
    if (memo[n] !== -1) return memo[n];

    // Case 1: Send two fastest people first 
    // and the fastest one returns
    let option1 = times[1] + times[0] 
                 + times[n - 1] + times[1];

    // Case 2: Send two slowest people first 
    // and the second fastest returns
    let option2 = times[n - 1] + times[0] 
                  + times[n - 2] + times[0];

    // Recur for the remaining people after either case
    let result = Math.min(
        option1 + minCrossingTime(times, n - 2, memo),
        option2 + minCrossingTime(times, n - 2, memo)
    );

    // Store result in memoization array
    memo[n] = result;
    return result;
}

function bridgeAndTorch(times) {
    times.sort((a, b) => a - b);
    let n = times.length;

    // Array to store results for memoization, 
    // initialized to -1
    let memo = new Array(n + 1).fill(-1);
    
    return minCrossingTime(times, n, memo);
}

const times = [10, 20, 30];
const result = bridgeAndTorch(times);
console.log(result);

Output
60

Using Bottom-Up DP (Tabulation) - O(nlogn) Time and O(n) Space

In this tabulation approach, we iteratively build up the solution instead of a recursive breakdown, we store results for each count of people. We will create a 1D array dp[] of size n + 1. The state dp[i] represents the minimum crossing time needed for i people.

For dp[i], calculate the time for two cases:

  • Option 1: Send the two fastest people across, and have the fastest one return. option1 = times[1] + times[0] + times[i - 1] + times[1]
  • Option 2: Send the two slowest people across, and have the second fastest return. option2 = times[i - 1] + times[0] + times[i - 2] + times[0]

Then, calculate: dp[i] = min(dp[i - 2] + option1, dp[i - 2] + option2)

C++
// C++ code for Bridge and Torch problem
// using Tabulation
#include <bits/stdc++.h>
using namespace std;

// Function to calculate minimum crossing 
// time using tabulation
int bridgeAndTorch(vector<int>& times) {
    sort(times.begin(), times.end());
    int n = times.size();

    // Create a dp vector to store minimum crossing 
    // times for each count of people
    vector<int> dp(n + 1, INT_MAX);
    dp[1] = times[0];
    if (n > 1) dp[2] = times[1];
    if (n > 2) dp[3] = times[0] + times[1] + times[2];

    // Fill dp array iteratively for 
    // each count of people
    for (int i = 4; i <= n; i++) {
      
        // Case 1: Send two fastest people first 
        // and the fastest returns
        int option1 = times[1] + times[0] + 
                        times[i - 1] + times[1];
        
        // Case 2: Send two slowest people first
        // and the second fastest returns
        int option2 = times[i - 1] + times[0] 
                       + times[i - 2] + times[0];

        // Minimum time required for i people
        dp[i] = min(dp[i - 2] + option1, 
                         dp[i - 2] + option2);
    }

    return dp[n];
}

int main() {
  
    vector<int> times = {10, 20, 30};
    cout << bridgeAndTorch(times) << endl;
    return 0;
}
Java
// Java code for Bridge and Torch problem
// using Tabulation
import java.util.*;

class GfG {

    // Function to calculate minimum crossing 
    // time using tabulation
    static int bridgeAndTorch(ArrayList<Integer> times) {
        Collections.sort(times);
        int n = times.size();

        // Create a dp array to store minimum crossing 
        // times for each count of people
        int[] dp = new int[n + 1];
        Arrays.fill(dp, Integer.MAX_VALUE);
        dp[1] = times.get(0);
        if (n > 1) dp[2] = times.get(1);
        if (n > 2) dp[3] = times.get(0) 
                     + times.get(1) + times.get(2);

        // Fill dp array iteratively for 
        // each count of people
        for (int i = 4; i <= n; i++) {
          
            // Case 1: Send two fastest people first 
            // and the fastest returns
            int option1 = times.get(1) + times.get(0) + 
                            times.get(i - 1) + times.get(1);
            
            // Case 2: Send two slowest people first
            // and the second fastest returns
            int option2 = times.get(i - 1) + times.get(0) 
                           + times.get(i - 2) + times.get(0);

            // Minimum time required for i people
            dp[i] = Math.min(dp[i - 2] + option1, 
                             dp[i - 2] + option2);
        }

        return dp[n];
    }

    public static void main(String[] args) {
      
        ArrayList<Integer> times 
          = new ArrayList<>(Arrays.asList(10, 20, 30));
      
        System.out.println(bridgeAndTorch(times));
    }
}
Python
# Python code for Bridge and Torch problem
# using Tabulation

def bridge_and_torch(times):
    times.sort()
    n = len(times)

    # Create a dp list to store minimum crossing
    # times for each count of people
    dp = [float('inf')] * (n + 1)
    dp[1] = times[0]
    if n > 1:
        dp[2] = times[1]
    if n > 2:
        dp[3] = times[0] + times[1] + times[2]

    # Fill dp list iteratively for
    # each count of people
    for i in range(4, n + 1):
      
        # Case 1: Send two fastest people first
        # and the fastest returns
        option1 = times[1] + times[0] + \
                    times[i - 1] + times[1]
        
        # Case 2: Send two slowest people first
        # and the second fastest returns
        option2 = times[i - 1] + times[0] + \
                   times[i - 2] + times[0]

        # Minimum time required for i people
        dp[i] = min(dp[i - 2] + option1, 
                         dp[i - 2] + option2)

    return dp[n]

if __name__ == "__main__":
  
    times = [10, 20, 30]
    print(bridge_and_torch(times))
C#
// C# code for Bridge and Torch problem
// using Tabulation
using System;
using System.Collections.Generic;

class GfG {
    
    // Function to calculate minimum crossing 
    // time using tabulation
    static int BridgeAndTorch(List<int> times) {
        times.Sort();
        int n = times.Count;

        // Create a dp array to store minimum crossing 
        // times for each count of people
        int[] dp = new int[n + 1];
        Array.Fill(dp, int.MaxValue);
        
        dp[1] = times[0];
        if (n > 1) dp[2] = times[1];
        if (n > 2) dp[3] = times[0] + times[1] + times[2];

        // Fill dp array iteratively for 
        // each count of people
        for (int i = 4; i <= n; i++) {
            
            // Case 1: Send two fastest people first 
            // and the fastest returns
            int option1 = times[1] + times[0] + 
                          times[i - 1] + times[1];
            
            // Case 2: Send two slowest people first
            // and the second fastest returns
            int option2 = times[i - 1] + times[0] + 
                          times[i - 2] + times[0];

            // Minimum time required for i people
            dp[i] = Math.Min(dp[i - 2] + option1, 
                             dp[i - 2] + option2);
        }

        return dp[n];
    }

   static void Main() {
        List<int> times = new List<int> { 10, 20, 30 };
        Console.WriteLine(BridgeAndTorch(times));
    }
}
JavaScript
// JavaScript code for Bridge and Torch problem
// using Tabulation

function bridgeAndTorch(times) {
    times.sort((a, b) => a - b);
    const n = times.length;

    // Create a dp array to store minimum crossing 
    // times for each count of people
    const dp = Array(n + 1).fill(Number.MAX_SAFE_INTEGER);
    dp[1] = times[0];
    if (n > 1) dp[2] = times[1];
    if (n > 2) dp[3] = times[0] + times[1] + times[2];

    // Fill dp array iteratively for 
    // each count of people
    for (let i = 4; i <= n; i++) {
        
        // Case 1: Send two fastest people first 
        // and the fastest returns
        const option1 = times[1] + times[0] + 
                        times[i - 1] + times[1];
        
        // Case 2: Send two slowest people first
        // and the second fastest returns
        const option2 = times[i - 1] + times[0] + 
                        times[i - 2] + times[0];

        // Minimum time required for i people
        dp[i] = Math.min(dp[i - 2] + option1, 
                         dp[i - 2] + option2);
    }

    return dp[n];
}

const times = [10, 20, 30];
console.log(bridgeAndTorch(times));

Output
60

Using Space Optimized DP - O(nlogn) Time and O(1) Space

In the previous dynamic programming approach, we derived a relation between states using a 1D array dp[]. However, we can observe that each state calculation only depends on the results from the last two states. Thus, instead of storing all states, we only need to keep track of two previous values. We only need the last two values (dp[i-2] and dp[i-1]) to calculate the current state dp[i].

So we can use three variables:

  • prev2 for dp[i-2]
  • prev1 for dp[i-1]
  • curr for dp[i]

For each iteration, calculate curr using the state relation above, then update prev2 and prev1:

  • prev2 = prev1
  • prev1 = curr

At the end, curr will hold the minimum crossing time for all n people.

C++
// C++ code for Bridge and Torch problem
// using Space Optimized DP
#include <bits/stdc++.h>
using namespace std;

// Function to calculate minimum crossing 
// time with space optimization
int bridgeAndTorch(vector<int>& times) {
    sort(times.begin(), times.end());
    int n = times.size();

    if (n == 1) return times[0];
    if (n == 2) return times[1];
    if (n == 3) return times[0] + times[1] + times[2];

    // Variables to store the minimum crossing 
    // times for the last two calculations
    int prev2 = times[0];
    int prev1 = times[1];
    int curr = times[0] + times[1] + times[2];

    // Calculate minimum crossing time iteratively
    for (int i = 4; i <= n; i++) {
      
        // Case 1: Send two fastest people 
        //first and the fastest one returns
        int option1 = times[1] + times[0] 
                   + times[i - 1] + times[1];

        // Case 2: Send two slowest people first 
        // and the second fastest returns
        int option2 = times[i - 1] + times[0] 
                     + times[i - 2] + times[0];

        // Calculate the minimum crossing
        // time for i people
        curr = min(prev2 + option1, prev2 + option2);

        // Update the values for the 
        // next iteration
        prev2 = prev1;
        prev1 = curr;
    }

    return curr;
}

int main() {
  
    vector<int> times = {10, 20, 30};
    cout << bridgeAndTorch(times) << endl;
    return 0;
}
Java
// Java code for Bridge and Torch problem
// using Space Optimized DP
import java.util.*;

class GfG {

    // Function to calculate minimum crossing 
    // time with space optimization
    static int bridgeAndTorch(ArrayList<Integer> times) {
        Collections.sort(times);
        int n = times.size();

        if (n == 1) return times.get(0);
        if (n == 2) return times.get(1);
        if (n == 3) return times.get(0) 
                 + times.get(1) + times.get(2);

        // Variables to store the minimum crossing 
        // times for the last two calculations
        int prev2 = times.get(0);
        int prev1 = times.get(1);
        int curr = times.get(0) + times.get(1) + times.get(2);

        // Calculate minimum crossing time iteratively
        for (int i = 4; i <= n; i++) {
          
            // Case 1: Send two fastest people 
            // first and the fastest one returns
            int option1 = times.get(1) + times.get(0) 
                       + times.get(i - 1) + times.get(1);

            // Case 2: Send two slowest people first 
            // and the second fastest returns
            int option2 = times.get(i - 1) + times.get(0) 
                         + times.get(i - 2) + times.get(0);

            // Calculate the minimum crossing
            // time for i people
            curr = Math.min(prev2 + option1, prev2 + option2);

            // Update the values for the 
            // next iteration
            prev2 = prev1;
            prev1 = curr;
        }

        return curr;
    }
  
    public static void main(String[] args) {
      
        ArrayList<Integer> times 
          = new ArrayList<>(Arrays.asList(10, 20, 30));
      
        System.out.println(bridgeAndTorch(times));
    }
}
Python
# Python code for Bridge and Torch problem
# using Space Optimized DP

def bridge_and_torch(times):
    times.sort()
    n = len(times)

    if n == 1:
        return times[0]
    if n == 2:
        return times[1]
    if n == 3:
        return times[0] + times[1] + times[2]

    # Variables to store the minimum crossing 
    # times for the last two calculations
    prev2 = times[0]
    prev1 = times[1]
    curr = times[0] + times[1] + times[2]

    # Calculate minimum crossing time iteratively
    for i in range(4, n + 1):
      
        # Case 1: Send two fastest people 
        # first and the fastest one returns
        option1 = times[1] + times[0] \
                         + times[i - 1] + times[1]

        # Case 2: Send two slowest people first 
        # and the second fastest returns
        option2 = times[i - 1] + times[0] \
                         + times[i - 2] + times[0]

        # Calculate the minimum crossing
        # time for i people
        curr = min(prev2 + option1, prev2 + option2)

        # Update the values for the 
        # next iteration
        prev2 = prev1
        prev1 = curr

    return curr
  
if __name__ == "__main__":
  
    times = [10, 20, 30]
    print(bridge_and_torch(times))
C#
// C# code for Bridge and Torch problem
// using Space Optimized DP
using System;
using System.Collections.Generic;

class GfG {
    
    // Function to calculate minimum crossing 
    // time using tabulation
    static int BridgeAndTorch(List<int> times) {
        times.Sort();
        int n = times.Count;

        if (n == 1) return times[0];
        if (n == 2) return times[1];
        if (n == 3) return times[0] + times[1] + times[2];

        // Variables to store the minimum crossing 
        // times for the last two calculations
        int prev2 = times[0];
        int prev1 = times[1];
        int curr = times[0] + times[1] + times[2];

        // Calculate minimum crossing time iteratively
        for (int i = 4; i <= n; i++) {
          
            // Case 1: Send two fastest people 
            // first and the fastest one returns
            int option1 = times[1] + times[0] 
                       + times[i - 1] + times[1];

            // Case 2: Send two slowest people first 
            // and the second fastest returns
            int option2 = times[i - 1] + times[0] 
                         + times[i - 2] + times[0];

            // Calculate the minimum crossing
            // time for i people
            curr = Math.Min(prev2 + option1, prev2 + option2);

            // Update the values for the 
            // next iteration
            prev2 = prev1;
            prev1 = curr;
        }

        return curr;
    }

    static void Main() {
        List<int> times = new List<int> { 10, 20, 30 };
        Console.WriteLine(BridgeAndTorch(times));
    }
}
JavaScript
// JavaScript code for Bridge and Torch problem
// using Space Optimized DP

function bridgeAndTorch(times) {
    times.sort((a, b) => a - b);
    const n = times.length;

    if (n === 1) return times[0];
    if (n === 2) return times[1];
    if (n === 3) return times[0] + times[1] + times[2];

    // Variables to store the minimum crossing 
    // times for the last two calculations
    let prev2 = times[0];
    let prev1 = times[1];
    let curr = times[0] + times[1] + times[2];

    // Calculate minimum crossing time iteratively
    for (let i = 4; i <= n; i++) {
      
        // Case 1: Send two fastest people 
        // first and the fastest one returns
        const option1 = times[1] + times[0] 
                     + times[i - 1] + times[1];

        // Case 2: Send two slowest people first 
        // and the second fastest returns
        const option2 = times[i - 1] + times[0] 
                     + times[i - 2] + times[0];

        // Calculate the minimum crossing
        // time for i people
        curr = Math.min(prev2 + option1, prev2 + option2);

        // Update the values for the 
        // next iteration
        prev2 = prev1;
        prev1 = curr;
    }

    return curr;
}

const times = [10, 20, 30];
console.log(bridgeAndTorch(times));

Output
60



Next Article

Similar Reads