Sponsored
Sponsored
This approach uses a dynamic programming strategy to determine the minimum cost. The idea is to leverage a DP array where dp[i] represents the minimum cost to paint up to the i-th wall. For each wall, we decide whether to use only the paid painter or to also utilize the free painter effectively when paid painter is occupied.
Time Complexity: O(n^2), Space Complexity: O(n)
1def minCost(cost, time):
2 n = len(cost)
3 dp = [float('inf')] * (n+1)
4 dp[0] = 0
5
6 for i in range(n):
7 occupied = 0
8 for j in range(i + 1, n + 1):
9 if occupied >= time[i]:
10 dp[j] = min(dp[j], dp[i] + cost[j-1])
11 break
12 occupied += time[i]
13
14 return dp[n]
15
16# Example usage
17cost = [1, 2, 3, 2]
18time = [1, 2, 3, 2]
19print(minCost(cost, time))
This Python solution utilizes a list to manage the state of minimum cost to paint up to each wall by assessing which painter to use based on availability and cost-effectiveness.
This approach leverages a greedy strategy, prioritizing the choice that minimizes cost per time unit. By sorting or considering smallest cost per time unit, we attempt to reach a solution that overall minimizes the total cost.
Time Complexity: O(n log n), Space Complexity: O(n)
1using System;
2using System.Collections.Generic;
class Program {
class Pair : IComparable<Pair> {
public int cost, time;
public Pair(int c, int t) {
cost = c;
time = t;
}
public int CompareTo(Pair other) {
return ((double)cost / time).CompareTo((double)other.cost / other.time);
}
}
static int MinCost(int[] cost, int[] time) {
List<Pair> ratios = new List<Pair>();
for (int i = 0; i < cost.Length; i++) {
ratios.Add(new Pair(cost[i], time[i]));
}
ratios.Sort();
int totalCost = 0;
int occupiedTime = 0;
foreach (Pair pair in ratios) {
if (occupiedTime < pair.time) {
totalCost += pair.cost;
occupiedTime += pair.time;
}
}
return totalCost;
}
static void Main() {
int[] cost = {1, 2, 3, 2};
int[] time = {1, 2, 3, 2};
Console.WriteLine(MinCost(cost, time));
}
}
This C# solution uses a list of custom Pair objects sorted based on their efficiency (cost/time). This allows painting order to be optimized, achieving a minimum cost solution.