Skip to content

Latest commit

 

History

History
48 lines (28 loc) · 2.08 KB

10-05-2023.md

File metadata and controls

48 lines (28 loc) · 2.08 KB

Algorithms: Coding Puzzles

Title:

Question 4: Find the minimum cost of based on the array

Language:

Python

Algorithm:

  1. The minCost function takes a list of efficiency values of workers as input.

  2. The sort method is called on the efficiency list to sort it in ascending order.

  3. The variable min_cost is initialized to be the maximum possible value (float('inf')), to ensure that the first calculated cost will always be less than min_cost.

  4. The function iterates through each worker to be excluded using a for loop, with the loop variable i being unused.

  5. For each excluded worker, the function calculates the total cost of the pairs of remaining workers using a list comprehension and the sum function. The range function generates indices for the list of workers in steps of 2, and the abs function calculates the absolute difference between the efficiencies of adjacent workers in each pair.

  6. The current cost is compared to the current minimum cost using the min function, and the minimum of the two is stored in min_cost.

  7. The list of efficiencies is rotated by removing the first element with the pop method and appending it to the end of the list with the append method. This ensures that the next iteration of the for loop excludes the next worker in the list.

  8. The minimum cost of completing the task is returned after all workers have been excluded and all costs have been calculated.

  9. Overall, the function calculates the minimum cost of completing a task by pairing workers with similar efficiencies, and then finds the minimum cost by trying all possible rotations of the list of efficiencies.

Code:

def minCost(efficiency):
    efficiency.sort()
    min_cost = float('inf')

    for i in range(len(efficiency)):
        cost = sum(abs(efficiency[j] - efficiency[j+1]) for j in range(0, len(efficiency)-1, 2))
        min_cost = min(min_cost, cost)
        efficiency.append(efficiency.pop(0))

    return min_cost

Solution:

The minimum cost is 475