You are given two 0-indexed integer arrays, cost and time, of size n representing the costs and the time taken to paint n different walls respectively. There are two painters available:
ith wall in time[i] units of time and takes cost[i] units of money.1 unit of time at a cost of 0. But the free painter can only be used if the paid painter is already occupied.Return the minimum amount of money required to paint the n walls.
Example 1:
Input: cost = [1,2,3,2], time = [1,2,3,2] Output: 3 Explanation: The walls at index 0 and 1 will be painted by the paid painter, and it will take 3 units of time; meanwhile, the free painter will paint the walls at index 2 and 3, free of cost in 2 units of time. Thus, the total cost is 1 + 2 = 3.
Example 2:
Input: cost = [2,3,4,2], time = [1,1,1,1] Output: 4 Explanation: The walls at index 0 and 3 will be painted by the paid painter, and it will take 2 units of time; meanwhile, the free painter will paint the walls at index 1 and 2, free of cost in 2 units of time. Thus, the total cost is 2 + 2 = 4.
Constraints:
1 <= cost.length <= 500cost.length == time.length1 <= cost[i] <= 1061 <= time[i] <= 500This 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.
This C solution implements a dynamic programming approach. It uses a 'dp' array where each index i captures the minimum cost to paint walls up to that point. The loop iteratively decides whether to utilize the paid or free painter based on occupancy.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n^2), Space Complexity: O(n)
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.
This C greedy approach calculates ratios of cost per time unit and sorts them to choose the painting sequence that increases efficiency, minimizing the cost.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n log n), Space Complexity: O(n)
| Approach | Complexity |
|---|---|
| Approach 1: Dynamic Programming | Time Complexity: O(n^2), Space Complexity: O(n) |
| Approach 2: Greedy Strategy | Time Complexity: O(n log n), Space Complexity: O(n) |
Walls and Gates - Multi-Source BFS - Leetcode 286 - Python • NeetCode • 94,114 views views
Watch 9 more video solutions →Practice Painting the Walls with our built-in code editor and test cases.
Practice on FleetCode