Skip to content

Commit

Permalink
Create Minimum Cost to Make Array Equal.py
Browse files Browse the repository at this point in the history
  • Loading branch information
SamirPaulb authored Oct 23, 2022
1 parent 2b8d678 commit 625dac1
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions 11_Binary-Search/Minimum Cost to Make Array Equal.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# https://leetcode.com/problems/minimum-cost-to-make-array-equal/

class Solution:
def minCost(self, nums: List[int], cost: List[int]) -> int:
def cal_cost(target):
ans = 0
for n, c in zip(nums, cost):
ans += abs(target - n) * c
return ans

low = min(nums); high = max(nums)
while low <= high:
mid = low + (high - low) // 2
cur_cost = cal_cost(mid)
right_cost = cal_cost(mid + 1)

if cur_cost < right_cost:
high = mid - 1
else:
low = mid + 1

return cal_cost(low)


# Time: O(N log(N))
# Space: O(1)

0 comments on commit 625dac1

Please sign in to comment.