Advertisement
rajeshinternshala

Untitled

Jan 8th, 2024
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.52 KB | None | 0 0
  1. import heapq
  2.  
  3. def min_cost_to_reduce_array(nums):
  4.     heapq.heapify(nums)  # Convert the input list into a min-heap
  5.     total_cost = 0
  6.  
  7.     while len(nums) > 1:
  8.         # Extract the two minimum elements from the heap
  9.         first = heapq.heappop(nums)
  10.         second = heapq.heappop(nums)
  11.        
  12.         # Calculate the cost of the current move
  13.         cost = first + second
  14.         total_cost += cost
  15.        
  16.         # Add the sum back to the heap
  17.         heapq.heappush(nums, cost)
  18.    
  19.     return total_cost
  20.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement