Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Minimum Amount to Paint the Walls
Next article icon

Minimum Amount to Paint the Walls

Last Updated : 21 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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: A paid painter that paints the ith wall in time[i] units of time and takes cost[i] units of money. A free painter that paints any wall in 1 unit of time at a cost of 0. But the free painter can only be used if the paid painter is already occupied. The task is to return the minimum amount of money required to paint the n walls.

Examples:

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.

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.

[Expected Approach] Using Memoization - O(n2) time and O(n2) space

The idea is that we want to prioritize using the paid painter for walls that are cheaper and take longer to paint because this will help us to use the free painter to work for longer time. This looks like a greedy problem but formulating into strategy is difficult because each decision impacts subsequent choices. Determining which walls to pay for and which to allocate to the free painter becomes complex. We will use dynamic programming to explore all possible decisions.

Step-by-step approach:

  • Let dp(i, remain) represent the minimum cost to paint remain walls starting from index i. There are two base cases:
    • If remain <= 0: All walls are painted, return 0.
    • If i == n: This represents no more walls to assign, return a large value (infinity).
  • For the ith wall, we have two options. We can either hire the paid painter for this wall or not hire them.
    • If we hire painter for ith wall then cost would be cost[i] + dp(i + 1, remain - 1 - time[i])
    • If we don't hire for ith wall then cost would be dp(i + 1, remain) and we simply move to the next index.

Below is the implementation of the above approach

C++
#include <bits/stdc++.h> using namespace std;  // Recursive function to compute minimum cost using DP int helper(int i, int remain, vector<vector<int>> & memo,             vector<int> &cost, vector<int> &time) {     // Base case: If no more walls need to be painted     if (remain <= 0) return 0;      // Base case: No more walls to consider     if (i == cost.size()) return 1e9;      // Check if result is already in memo     if (memo[i][remain] != -1) return memo[i][remain];      // Option 1: Use paid painter for the ith wall     int paint = cost[i] + helper(i + 1, remain - 1                 - time[i], memo, cost, time);      // Option 2: Skip the ith wall     int dontPaint = helper(i + 1, remain, memo, cost,                             time);      // Store the minimum of the two options in memo     memo[i][remain] = min(paint, dontPaint);     return memo[i][remain]; }  // Initialize memoization and start the DP process int minCost(vector<int> &cost, vector<int> &time) {     int n = cost.size();      // Initialize memo table with -1     vector<vector<int>> memo(n, vector<int>(n + 1, -1));      // Start DP from the first wall     return helper(0, n, memo, cost, time); }  int main() {     vector<int> cost1 = {1, 2, 3, 2};     vector<int> time1 = {1, 2, 3, 2};     cout << "Minimum cost: " << minCost(cost1, time1)           << endl;      return 0; } 
Java
import java.util.Arrays;  class GfG{      // Recursive function to compute minimum cost using DP     static int helper(int i, int remain,                              int[][] memo, int[] cost,                              int[] time)     {         // Base case: If no more walls need to be painted         if (remain <= 0)             return 0;          // Base case: No more walls to consider         if (i == cost.length)             return 1000000000;          // Check if result is already in memo         if (memo[i][remain] != -1)             return memo[i][remain];          // Option 1: Use paid painter for the ith wall         int paint = cost[i]                     + helper(i + 1, remain - 1 - time[i],                              memo, cost, time);          // Option 2: Skip the ith wall         int dontPaint             = helper(i + 1, remain, memo, cost, time);          // Store the minimum of the two options in memo         memo[i][remain] = Math.min(paint, dontPaint);         return memo[i][remain];     }      // Initialize memoization and start the DP process     static int minCost(int[] cost, int[] time)     {         int n = cost.length;          // Initialize memo table with -1         int[][] memo = new int[n][n + 1];         for (int[] row : memo) {             Arrays.fill(row, -1);         }          // Start DP from the first wall         return helper(0, n, memo, cost, time);     }      public static void main(String[] args)     {         int[] cost1 = { 1, 2, 3, 2 };         int[] time1 = { 1, 2, 3, 2 };         System.out.println("Minimum cost: "                            + minCost(cost1, time1));     } } 
Python
# Recursive function to compute minimum cost def helper(i, remain, memo, cost, time):     # Base case: No more walls need painting     if remain <= 0:         return 0     # Base case: No more walls to consider     if i == len(cost):         return float('inf')      # Check if result is in memo     if memo[i][remain] != -1:         return memo[i][remain]      # Option 1: Use paid painter for ith wall     paint = cost[i] + helper(i + 1, remain - 1                               - time[i], memo, cost, time)      # Option 2: Skip the ith wall     dont_paint = helper(i + 1, remain, memo, cost, time)      # Store the minimum of the two options in memo     memo[i][remain] = min(paint, dont_paint)     return memo[i][remain]  # Function to start the DP process def min_cost(cost, time):     n = len(cost)     # Initialize memo table with -1     memo = [[-1] * (n + 1) for _ in range(n)]     # Start DP from the first wall     return helper(0, n, memo, cost, time)  cost1 = [1, 2, 3, 2] time1 = [1, 2, 3, 2] print("Minimum cost:", min_cost(cost1, time1)) 
JavaScript
function helper(i, remain, memo, cost, time) {     // Base case: If no more walls need to be painted     if (remain <= 0)         return 0;      // Base case: No more walls to consider     if (i === cost.length)         return Infinity;      // Check if result is already in memo     if (memo[i][remain] !== -1)         return memo[i][remain];      // Option 1: Use paid painter for the ith wall     let paint = cost[i]                 + helper(i + 1, remain - 1 - time[i], memo,                          cost, time);      // Option 2: Skip the ith wall     let dontPaint = helper(i + 1, remain, memo, cost, time);      // Store the minimum of the two options in memo     memo[i][remain] = Math.min(paint, dontPaint);     return memo[i][remain]; }  function minCost(cost, time) {     let n = cost.length;      // Initialize memo table with -1     let memo = Array.from({length : n},                           () => Array(n + 1).fill(-1));      // Start DP from the first wall     return helper(0, n, memo, cost, time); }  // Example usage let cost1 = [ 1, 2, 3, 2 ]; let time1 = [ 1, 2, 3, 2 ]; console.log("Minimum cost: " + minCost(cost1, time1)); 

Output
Minimum cost: 3 

Time Complexity: O(n^2), where n is the number of walls.
Auxiliary Space: O(n^2)



Next Article
Minimum Amount to Paint the Walls

K

krishna_g
Improve
Article Tags :
  • Dynamic Programming
  • DSA
  • DE Shaw
Practice Tags :
  • DE Shaw
  • Dynamic Programming

Similar Reads

    Minimum rectangles to cover all points
    Given a 2D array points[][], where points[i] = [xi, yi]. The task is to find the minimum number of rectangles of width `w` or less needed to cover all points in a given 2D array, where each rectangle's lower end is at (x1, 0) and upper end at (x2, y2) with x1 = 0. A point is covered if it's within o
    4 min read
    Minimum lines to cover all points
    Given N points in 2-dimensional space, we need to print the count of the minimum number of lines which traverse through all these N points and which go through a specific (xO, yO) point also.Examples: If given points are (-1, 3), (4, 3), (2, 1), (-1, -2), (3, -3) and (xO, yO) point is (1, 0) i.e. ev
    9 min read
    Calculate total wall area of houses painted
    Given integers N, L and W representing number of rows and length and width of houses in each row, and an array Heights[], representing the height of each house, the task is to find the total area of the outer walls required to be painted if the adjacent houses share a common wall. Examples: Input: N
    7 min read
    Minimum squares to cover a rectangle
    Given a rectangle with length l and breadth b, we need to find the minimum number of squares that can cover the surface of the rectangle, given that each square has a side of length a. It is allowed to cover the surface larger than the rectangle, but the rectangle has to be covered. It is not allowe
    9 min read
    Minimum time to reduce all the elements to zero
    Given an array of positive integers arr[] of size N. Every second, all the positive values of the array decrease by 1 until they reach zero. Apart from this, we can also perform a special operation in one second to reduce any element by K. If reducing an element by K, makes it negative simply reduce
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences