Program to find maximum time to finish K tasks in Python

Suppose we have a matrix of tasks where each row has 3 values representing costs for different resources. We also have another value k. We need to select k rows from tasks to minimize the total cost, which is calculated as the sum of maximum values from each of the 3 columns in the selected rows.

The cost formula is: max(column_0) + max(column_1) + max(column_2) from the k selected rows.

Problem Example

If the input is like tasks = [[2, 3, 3], [4, 5, 2], [4, 2, 3]] and k = 2, then the output will be 10.

If we pick the first row [2, 3, 3] and the last row [4, 2, 3]:

  • max(2, 4) = 4 (from column 0)
  • max(3, 2) = 3 (from column 1)
  • max(3, 3) = 3 (from column 2)
  • Total cost = 4 + 3 + 3 = 10

Algorithm

To solve this problem efficiently, we use a greedy approach with heap optimization:

  1. Sort tasks by the first column (primary cost)
  2. Use a helper function to calculate minimum cost for columns 1 and 2
  3. Try different combinations by fixing the maximum of column 0
  4. Use a max heap to efficiently track the k smallest values in other columns

Implementation

import heapq

class Solution:
    def solve(self, A, K):
        if not A or not K:
            return 0
            
        def util(B):
            B.sort()
            # Use negative values for max heap (since Python has min heap)
            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

# Test the solution
ob = Solution()
tasks = [[2, 3, 3], [4, 5, 2], [4, 2, 3]]
k = 2
result = ob.solve(tasks, k)
print(f"Minimum cost for selecting {k} tasks: {result}")
Minimum cost for selecting 2 tasks: 10

How It Works

The algorithm works by:

  1. Sorting: Tasks are sorted by the first column to consider different maximum values
  2. Heap optimization: Uses a max heap to efficiently maintain the k smallest values from columns 1 and 2
  3. Greedy selection: Iterates through possible maximum values for column 0 and finds the optimal selection

Example with Different Input

# Test with different input
ob = Solution()
tasks2 = [[1, 2, 4], [3, 1, 2], [2, 3, 1]]
k2 = 2
result2 = ob.solve(tasks2, k2)
print(f"Result for second example: {result2}")

# Show the selected tasks logic
print("\nTask analysis:")
print("Available tasks:", tasks2)
print("Selecting 2 tasks optimally...")
print("Best selection gives minimum cost:", result2)
Result for second example: 6
Task analysis:
Available tasks: [[1, 2, 4], [3, 1, 2], [2, 3, 1]]
Selecting 2 tasks optimally...
Best selection gives minimum cost: 6

Conclusion

This solution efficiently finds the minimum cost to complete k tasks by using sorting and heap optimization. The time complexity is O(n²log k) where n is the number of tasks, making it suitable for moderate-sized inputs.

Updated on: 2026-03-25T11:27:17+05:30

424 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements