Program to find maximum time to finish K tasks in Python

PythonServer Side ProgrammingProgramming

Suppose we have a matrix of tasks where each row has 3 values. We also have another value k. We have to select k rows from tasks, call it S, such that the following sum is minimized and return the sum as: maximum of (S[0, 0], S[1, 0], ...S[k - 1, 0]) + maximum of (S[0, 1], S[1, 1], ...S[k - 1, 1]) + maximum of (S[0, 2], S[1, 2], ...S[k - 1, 2]) We can also say like: Each of the 3 columns contribute to a cost, and is calculated by taking the max value of that column in S. The max of an empty list is 0.

So, if the input is like tasks = [[2, 3, 3], [4, 5, 2], [4, 2, 3] ], k = 2, then the output will be 10, as if we pick the first row and the last row. The total sum will be S = [[2,3,3],[4,2,3]] max(S[0,0], S[1,0]) = 4 + max(S[0,1], S[1,1]) = 3 + max(S[0,2], S[1,2]) = 3 = 10

To solve this, we will follow these steps −

  • Define a function util() . This will take B
  • sort the list B
  • yheap := a list with -B[i, 1] for each i in range 0 to K-1
  • heapify yheap
  • ans := B[K - 1, 0] + (-yheap[0])
  • for i in range K to size of B, do
    • x := B[i, 0]
    • replace yheap by -B[i,1]
    • set size of yheap is same as K
    • y := -yheap[0]
    • ans := minimum of ans and x + y
  • return ans
  • From the main method do the following −
  • if A is empty or K is 0, then
    • return 0
  • sort the list A
  • B := make a list of pairs [A[i, 1], A[i, 2]] for each i in range 0 to K-1
  • ans := A[K - 1, 0] + maximum of y for each (y, z) in B + maximum of z for each(y, z) in B
  • for i in range K to size of A, do
    • insert [A[i][1], A[i][2]] into B
    • ans = minimum of ans and A[i, 0] + util(B)
  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

import heapq
class Solution:
   def solve(self, A, K):
      if not A or not K:
         return 0
      def util(B):
         B.sort()
         yheap = [-B[i][1] for i in range(K)]
         heapq.heapify(yheap)
         ans = B[K - 1][0] + (-yheap[0])
         for i in range(K, len(B)):
            x = B[i][0] heapq.heappushpop(yheap, -B[i][1])
            assert len(yheap) == K
            y = -yheap[0]
         ans = min(ans, x + y)
         return ans
         A.sort()
         B = [[A[i][1], A[i][2]] for i in range(K)]
         ans = A[K - 1][0] + max(y for y, z in B) + max(z for y, z in B)
         for i in range(K, len(A)):
            B.append([A[i][1], A[i][2]])
            ans = min(ans, A[i][0] + util(B))
         return ans
ob = Solution()
tasks = [ [2, 3, 3], [4, 5, 2], [4, 2, 3] ]
k = 2
print(ob.solve(tasks, k))

Input

tasks = [
[2, 3, 3],
[4, 5, 2],
[4, 2, 3] ],
k = 2

Output

10
raja
Published on 19-Oct-2020 15:38:22
Advertisements