710260. Minimum Cost Car

Medium

Here is a detailed Markdown blog post for the "Minimum Cost Car" problem:

Minimum Cost Car

Summary

The minimum cost car problem involves finding the minimum total cost to travel between two cities. Given a set of cars with different costs and capacities, we need to find the optimal combination of cars that can accommodate all passengers traveling from one city to another.

Detailed Explanation

To solve this problem, we'll use dynamic programming to keep track of the minimum cost for each possible number of passengers. We'll also use an array to store the minimum cost for each passenger count.

Here's a step-by-step breakdown:

  1. Initialize an array dp of size n, where n is the maximum number of passengers, with all elements set to infinity.
  2. Set dp[0] = 0, since there's no cost to travel with 0 passengers.
  3. For each passenger count from 1 to n, iterate through the available cars and calculate the minimum cost for that passenger count.
  4. If a car can accommodate all passengers, add its cost to the current minimum cost.
  5. Update the minimum cost array with the calculated value.
  6. Find the minimum cost for the target number of passengers by traversing the dp array.

Here's an ASCII art diagram illustrating the dynamic programming approach:

  +---------------+
  |  dp[0] = 0    |
  +---------------+
           |
           |
           v
  +---------------+
  |  dp[1] = car1  |
  +---------------+
           |
           |
           v
  +---------------+
  |  dp[2] = car1  |
  |        + car2   |
  +---------------+
           ...

Optimized Solutions

Java

View on GeeksforGeeks
public int minCostCar(int[] cars, int passengers) {
    int n = cars.length;
    int[] dp = new int[n];
    Arrays.fill(dp, Integer.MAX_VALUE);
    dp[0] = 0;

    for (int i = 1; i < n; i++) {
        for (int j = 0; j <= i; j++) {
            if (cars[j] >= passengers) {
                int cost = cars[j];
                for (int k = j + 1; k <= i; k++) {
                    if (cars[k] >= passengers - j) {
                        cost += cars[k];
                        break;
                    }
                }
                dp[i] = Math.min(dp[i], cost);
            }
        }
    }

    return dp[passengers];
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.