Open In App

Minimum time required to complete exactly K tasks based on given order of task execution

Last Updated : 09 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a 2D array, arr[][] of size N, each row of which consists of the time required to complete 3 different types of tasks A, B, and C. The row elements arr[i][0], arr[i][1] and arr[i][2] are the time required to complete the ith task of type A, B and C respectively. The task is to find the minimum completion time to complete exactly K tasks from the array based on the following conditions:

  • The same type of task will operate at the same time.
  • Tasks of type B can be performed only when K tasks of type A have already been completed.
  • Tasks of type C can be performed only when K tasks of type B have already been completed.

Examples:

Input: N = 3, K = 2, arr[][] = {{1, 2, 2}, {3, 4, 1}, {3, 1, 2}}
Output:
Explanation: 
Minimum time required to complete K tasks of type A = min(max(arr[0][0], arr[2][0]), max(arr[0][0], arr[1][0]), max(arr[1][0], arr[2][0])) = min(max(1, 3), max(1, 3), max(3, 3)) 3
Minimum time required to complete K tasks of type B = max(arr[0][1], arr[2][1]) = 2
Therefore, select items 1 and 3 as the K tasks to be completed for minimum time.
Therefore, time to complete K tasks of type C = max(arr[0][2], arr[2][2]) = 2
Therefore, minimum time to complete K(= 2) of all types = 3 + 2 + 2 = 7

Input: N = 3, K = 3, arr[][] = {{2, 4, 5}, {4, 5, 4}, {3, 4, 5}} 
Output: 14

 

Approach: The problem can be solved using Recursion. The idea is to either select the ith row from the given array or not. The following are the recurrence relation.

MinTime(TA, TB, TC, K, i) = min(MinTime(max(arr[i][0], TA), max(arr[i][1], TB), max(arr[i][2], TC), K-1, i-1), MinTime(TA, TB, TC, K, i-1))

MinTime(TA, TB, TC, K, i) Stores the minimum time to complete K tasks.
i stores the position of the ith row of the given array elements.

Base Case: if K == 0:
return TA + TB + TC
if i <= 0:
return Infinite

Follow the steps below to solve the problem:

  1. Initialize a variable, say X and Y while traversing each row recursively using the above recurrence relation.
  2. X stores the minimum completion time by selecting the ith row of the given array.
  3. Y stores the minimum completion time by not selecting the ith row of the given array.
  4. Find the value of X and Y using the above-mentioned recurrence relation.
  5. Finally, return the value of min(X, Y) for every row.

Below is the implementation of the above approach:

C++




// C++ program to implement
// the above approach
#include<bits/stdc++.h>
using namespace std;
#define N 3
 
// Function to get the minimum
// completion time to select
// exactly K items
int MinTime(int arr[][N],int i, 
                int Ta, int Tb,
                int Tc, int K)
{
    // Base case
    if(K == 0) {
        return Ta + Tb + Tc;
    }
    if(i == 0)
        return INT_MAX;
         
    // Select the ith item
    int X = MinTime(arr, i - 1,
            max(Ta, arr[i - 1][0]),
            max(Tb, arr[i - 1][1]),
            max(Tc, arr[i - 1][2]), K -1);
     
    // Do not select the ith item
    int Y = MinTime(arr, i - 1,
                    Ta, Tb, Tc, K);
                     
    return min(X, Y);
}
 
// Driver Code
int main()
{
  int K = 2;
  int n = 3;
  int arr[N][N] = {{1, 2, 2} ,
                   {3, 4, 1} ,
                   {3, 1, 2}
                  };
   
  cout<<MinTime(arr, N, 0, 0, 0, K);
  return 0;
}


Java




// Java program to implement 
// the above approach
import java.util.*;
 
class GFG{
 
// Function to get the minimum
// completion time to select
// exactly K items
public static int MinTime(int arr[][], int i,
                          int Ta, int Tb,
                          int Tc, int K)
{
     
    // Base case
    if (K == 0)
    {
        return Ta + Tb + Tc;
    }
    if (i == 0)
        return Integer.MAX_VALUE;
 
    // Select the ith item
    int X = MinTime(arr, i - 1,
                    Math.max(Ta, arr[i - 1][0]),
                    Math.max(Tb, arr[i - 1][1]),
                    Math.max(Tc, arr[i - 1][2]), K - 1);
 
    // Do not select the ith item
    int Y = MinTime(arr, i - 1, Ta,
                    Tb, Tc, K);
 
    return Math.min(X, Y);
}
 
// Driver Code
public static void main(String args[])
{
    int K = 2;
    int n = 3;
    int arr[][] = { { 1, 2, 2 },
                    { 3, 4, 1 },
                    { 3, 1, 2 } };
 
    System.out.println(MinTime(arr, n, 0, 0, 0, K));
}
}
 
// This code is contributed by hemanth gadarla


Python3




# Python3 program to implement
# the above approach
N = 3
 
# Function to get the minimum
# completion time to select
# exactly K items
def MinTime(arr, i, Ta, Tb, Tc, K):
     
    # Base case
    if (K == 0):
        return Ta + Tb + Tc
    if (i == 0):
        return 10**9
 
    # Select the ith item
    X = MinTime(arr, i - 1,
            max(Ta, arr[i - 1][0]),
            max(Tb, arr[i - 1][1]),
            max(Tc, arr[i - 1][2]), K -1)
 
    # Do not select the ith item
    Y = MinTime(arr, i - 1,
                Ta, Tb, Tc, K)
 
    return min(X, Y)
 
# Driver Code
if __name__ == '__main__':
     
    K = 2
    n = 3
    arr = [ [ 1, 2, 2 ],
            [ 3, 4, 1 ],
            [ 3, 1, 2 ] ]
 
    print(MinTime(arr, N, 0, 0, 0, K))
 
# This code is contributed by mohit kumar 29


C#




// C# program to implement 
// the above approach
using System;
class GFG{
 
// Function to get the minimum
// completion time to select
// exactly K items
public static int MinTime(int [,]arr, int i,
                          int Ta, int Tb,
                          int Tc, int K)
{   
  // Base case
  if (K == 0)
  {
    return Ta + Tb + Tc;
  }
  if (i == 0)
    return int.MaxValue;
 
  // Select the ith item
  int X = MinTime(arr, i - 1,
                  Math.Max(Ta,
                           arr[i - 1, 0]),
                  Math.Max(Tb,
                           arr[i - 1, 1]),
                  Math.Max(Tc,
                           arr[i - 1, 2]),
                               K - 1);
 
  // Do not select the ith item
  int Y = MinTime(arr, i - 1, Ta,
                  Tb, Tc, K);
 
  return Math.Min(X, Y);
}
 
// Driver Code
public static void Main(String []args)
{
  int K = 2;
  int n = 3;
  int [,]arr = {{1, 2, 2},
                {3, 4, 1},
                {3, 1, 2}};
 
  Console.WriteLine(MinTime(arr, n, 0,
                            0, 0, K));
}
}
 
// This code is contributed by shikhasingrajput


Javascript




<script>
 
// Javascript program to implement 
// the above approach
 
// Function to get the minimum
// completion time to select
// exactly K items
function Mletime(arr, i, Ta, Tb, Tc, K)
{
      
    // Base case
    if (K == 0)
    {
        return Ta + Tb + Tc;
    }
    if (i == 0)
        return Number.MAX_VALUE;
  
    // Select the ith item
    let X = Mletime(arr, i - 1,
                    Math.max(Ta, arr[i - 1][0]),
                    Math.max(Tb, arr[i - 1][1]),
                    Math.max(Tc, arr[i - 1][2]), K - 1);
  
    // Do not select the ith item
    let Y = Mletime(arr, i - 1, Ta,
                    Tb, Tc, K);
  
    return Math.min(X, Y);
}
 
// Driver code
K = 2;
let n = 3;
let arr = [ [ 1, 2, 2 ],
            [ 3, 4, 1 ],
            [ 3, 1, 2 ] ];
 
document.write(Mletime(arr, n, 0, 0, 0, K));
 
// This code is contributed by splevel62 
 
</script>


Output

7

Time Complexity: O(2N)
Auxiliary Space: O(N)

Approach 2 :-

C++




#include <iostream>
#include <bits/stdc++.h>
 
using namespace std;
int MinTime(vector<vector<int>>& tasks, int k)
{
    // if k == 0 then return 0
    if (k == 0)
    {
        return 0;
    }
    vector<pair<int, pair<int, int>>> arr;
   
    // make a pair of pair DS
    for (auto t : tasks)
    {
        arr.push_back({t[0], {t[1], t[2]}});
    }
   
    // sort the pairs
    sort(arr.begin(), arr.end());
   
    // initialize the ans as INT_MAX/2
    int ans = INT_MAX / 2;
    for (int i = k - 1; i < arr.size(); i++)
    {
        vector<pair<int, int>> pr;
       
        // push the pairs into the pr vector
        for (int j = 0; j <= i; j++)
        {
            pr.push_back(arr[j].second);
        }
       
        // sort the pairs
        sort(pr.begin(), pr.end());
        
        // priority queue
        priority_queue<int> q;
        for (int j = 0; j < pr.size(); j++)
        {
            q.push(pr[j].second);
            if (q.size() > k)
            {
                q.pop();
            }
            if (q.size() == k)
            {
                ans = min(ans, arr[i].first + q.top() + pr[j].first);
            }
        }
    }
    return ans;
}
 
// Driver Code
int main() {
 
   int K = 2;
  int n = 3;
  vector<vector<int>> arr =
                  {{1, 2, 2} ,
                   {3, 4, 1} ,
                   {3, 1, 2}
                  };
    
  cout<<MinTime(arr,K)<<endl;
  //This code is given by Akshay Verma
  return 0;
}


Java




// Java program to implement 
// the above approach
import java.util.*;
class GFG
{
  static int MinTime(int[][] tasks, int k)
  {
 
    // if k == 0 then return 0
    if (k == 0)
    {
      return 0;
    }
    ArrayList<int[]> arr = new ArrayList<>();
 
    // make a pair of pair DS
    for (int[] t : tasks)
    {
      arr.add(new int[]{t[0], t[1], t[2]});
    }
 
    // sort the pairs
    Collections.sort(arr, (a, b)->a[0] - b[0]);
 
    // initialize the ans as INT_MAX/2
    int ans =Integer.MAX_VALUE / 2;
    for (int i = k - 1; i < arr.size(); i++)
    {
      ArrayList<int[]> pr = new ArrayList<>();
 
      // push the pairs into the pr vector
      for (int j = 0; j <= i; j++)
      {
        pr.add(new int[]{arr.get(j)[1],arr.get(j)[2]});
      }
 
      // sort the pairs
      Collections.sort(pr, (a, b)->a[0] - b[0]);
 
      // priority queue
      PriorityQueue<Integer> q = new PriorityQueue<>();
      for (int j = 0; j < pr.size(); j++)
      {
        q.add(pr.get(j)[1]);
        if (q.size() > k)
        {
          q.poll();
        }
        if (q.size() == k)
        {
          ans = Math.min(ans, arr.get(i)[0] +
                         q.peek() + pr.get(j)[0]);
        }
      }
    }
    return ans;
  }
 
  // Driver code
  public static void main (String[] args)
  {
    int K = 2;
    int n = 3;
    int arr[][] = { { 1, 2, 2 },
                   { 3, 4, 1 },
                   { 3, 1, 2 } };
 
    System.out.println(MinTime(arr,K));
 
  }
}
 
// This code is contributed by offbeat


Python3




# Python program to implement 
# the above approach
import sys
 
def MinTime(tasks,k):
   
   # if k == 0 then return 0
    if (k == 0):
        return 0
     
    arr = []
     
     # make a pair of pair DS
    for t in tasks:
        arr.append([t[0], t[1], t[2]])
     
     # sort the pairs
    arr.sort()
     
    # initialize the ans as INT_MAX/2
    ans = sys.maxsize//2
     
    for i in range(k - 1, len(arr)):
        pr = []
     
    # push the pairs into the pr vector
        for j in range(i+1):
            pr.append([arr[j][1],arr[j][2]])
         
         # sort the pairs
        pr.sort()
         
        # priority queue
        q = []
         
        for j in range(len(pr)):
            q.append(pr[j][1])
             
            if(len(q) > k):
                q.pop(0)
            if(len(q) == k):
                ans=min(ans, arr[i][0] + q[0] + pr[j][0])
    return ans
 
  # Driver code
K = 2
n = 3
 
arr = [[1, 2, 2], [ 3, 4, 1 ], [3, 1, 2 ]]
print(MinTime(arr, K))
 
# This code is contributed by unknown2108


C#




// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
class GFG {
    
  static int MinTime(int[,] tasks, int k)
  {
  
    // if k == 0 then return 0
    if (k == 0)
    {
      return 0;
    }
    List<List<int>> arr = new List<List<int>>();
  
    // make a pair of pair DS
    for(int i = 0; i < tasks.GetLength(0); i++)
    {
        arr.Add(new List<int>());
        for(int j = 0; j < tasks.GetLength(1); j++)
        {
         arr[i].Add(tasks[i,j]);  
        }
    }
  
    // initialize the ans as INT_MAX/2
    int ans = Int32.MaxValue / 2;
    for (int i = k - 1; i < arr.Count; i++)
    {
      List<List<int>> pr = new List<List<int>>();
  
      // push the pairs into the pr vector
      for (int j = 0; j <= i; j++)
      {
        pr.Add(new List<int>());
        pr[j].Add(arr[j][1]);
        pr[j].Add(arr[j][2]);
      }
  
      // priority queue
      List<int> q = new List<int>();
      for (int j = 0; j < pr.Count; j++)
      {
        q.Add(pr[j][1]);
        q.Sort();
        q.Reverse();
        if (q.Count > k)
        {
          q.RemoveAt(0);
        }
        if (q.Count == k)
        {
          ans = Math.Min(ans, arr[i][0] + q[0] + pr[j][0]) + 1;
        }
      }
    }
    return ans;
  }
 
  // Driver code
  static void Main() {
    int K = 2;
    int[,] arr = { { 1, 2, 2 },
                   { 3, 4, 1 },
                   { 3, 1, 2 } };
  
    Console.Write(MinTime(arr,K));
  }
}
 
// This code is contributed by decode2207.


Javascript




<script>
// Javascript program to implement
// the above approach
 
function MinTime(tasks,k)
{
    // if k == 0 then return 0
    if (k == 0)
    {
      return 0;
    }
    let arr = [];
  
    // make a pair of pair DS
    for (let t=0;t< tasks.length;t++)
    {
      arr.push([tasks[t][0], tasks[t][1], tasks[t][2]]);
    }
  
    // sort the pairs
    arr.sort(function(a,b){return a[0]-b[0];});
  
    // initialize the ans as INT_MAX/2
    let ans =Number.MAX_VALUE / 2;
    for (let i = k - 1; i < arr.length; i++)
    {
      let pr = [];
  
      // push the pairs into the pr vector
      for (let j = 0; j <= i; j++)
      {
        pr.push([arr[j][1],arr[j][2]]);
      }
  
      // sort the pairs
      pr.sort(function(a,b){return a[0]-b[0];});
  
      // priority queue
      let q = [];
      for (let j = 0; j < pr.length; j++)
      {
        q.push(pr[j][1]);
        if (q.length > k)
        {
          q.shift();
        }
        if (q.length == k)
        {
          ans = Math.min(ans, arr[i][0] +
                         q[0] + pr[j][0]);
        }
      }
    }
    return ans;
}
 
// Driver code
let K = 2;
let n = 3;
let arr=[[ 1, 2, 2 ],
                   [ 3, 4, 1 ],
                   [ 3, 1, 2 ]];
document.write(MinTime(arr,K));
 
 
// This code is contributed by patel2127
</script>


Output

7

Time Complexity :- O(N2logN)
Space Complexity:- O(N)



Similar Reads

Find time taken to execute the tasks in A based on the order of execution in B
Given two queues A and B, each of size N, the task is to find the minimum time taken to execute the tasks in A based on the order of execution in B where: If the task found at the front of queue B is at the front of queue A, then pop this task and execute it.If the task found at the front of queue B is not found at the front of queue A, then pop th
10 min read
Minimum time to complete at least K tasks when everyone rest after each task
Given an array arr[] of size N representing the time taken by a person to complete a task. Also, an array restTime[] which denotes the amount of time one person takes to rest after finishing a task. Each person is independent of others i.e. they can work simultaneously on different task at the same time. Given an integer K, the task is to find at l
9 min read
Minimum time required to complete all tasks with alteration of their order allowed
Given a string S consisting of N characters (representing the tasks to perform) and a positive integer K, the task is to find the minimum time required to complete all the given tasks in any order, given that each task takes one unit of time and each task of the same type must be performed at an interval of K units. Examples: Input: S = "AAABBB", K
8 min read
Minimum time required to complete all tasks without altering their order
Given a string S consisting of N characters (representing the tasks to perform) and a positive integer K, the task is to find the minimum time required to complete all the given tasks in the given order such that each task takes one unit of time and each task of the same type must be performed at an interval of K units. Examples: Input: S = "ABACCA
6 min read
Minimum cost to complete given tasks if cost of 1, 7 and 30 days are given
Given a sorted array arr[] consisting of N positive integers such that arr[i] represent the days in which a worker will work and an array cost[] of size 3 representing the salary paid to the workers for 1 day, 7 days and 30 days respectively, the task is to find the minimum cost required to have a worker for all the given days in arr[]. Examples: I
23 min read
Minimum time required to print given string from a circular container based on given conditions
Given a circular container consisting of lowercase alphabets from 'a' to 'z', a pointer pointing initially at alphabet 'a', and a string str, the task is to find the minimum time required to print the given string str from the circular container, based on following operations that can be performed on every character: Move the pointer one character
6 min read
Minimum time to finish tasks without skipping two consecutive
Given the time taken by n tasks. Find the minimum time needed to finish the tasks such that skipping of tasks is allowed, but can not skip two consecutive tasks. Examples : Input : arr[] = {10, 5, 7, 10} Output : 12 We can skip first and last task and finish these task in 12 min. Input : arr[] = {10} Output : 0 There is only one task and we can ski
10 min read
Find the order of execution of given N processes in Round Robin Scheduling
Given an array arr[] representing burst time of N processes scheduled using the Round Robin Algorithm with given quantum time Q. Assuming that all the process arrive at time t = 0, the task is to find the order in which the process execute. Examples: Input: arr[] = {3, 7, 4}, q = 3Output: 0 2 1Explanation:The order of execution is as follows P0, P1
12 min read
Find the tasks completed by soldiers based on their ranks
Given an array ranks[] of size N denoting the ranks of soldiers and tasks[] of size M where tasks[i] represent the amount of time (in seconds) required to complete ith task. Every second, a task enters into the system. Assigning tasks to soldiers depends on the rank of soldiers, the task will be assigned to a free soldier with the smallest rank, an
12 min read
Minimum work to be done per day to finish given tasks within D days
Given an array task[] of size N denoting amount of work to be done for each task, the problem is to find the minimum amount of work to be done on each day so that all the tasks can be completed in at most D days. Note: On one day work can be done for only one task. Examples: Input: task[] = [3, 4, 7, 15], D = 10Output: 4Explanation: Here minimum wo
9 min read