Skip to content

Commit

Permalink
feature: minimum cost to make array equal
Browse files Browse the repository at this point in the history
  • Loading branch information
solairerove committed Jun 21, 2023
1 parent dd123ce commit cacb0e1
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
24 changes: 24 additions & 0 deletions binary_search/MinimumCostToMakeArrayEqual.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from typing import List


# O(n * log(a)) time || O(1) space, a - range in nums
def min_cost(self, nums: List[int], cost: List[int]) -> int:
if min(nums) == max(nums):
return 0

def f(x):
return sum(abs(a - x) * c for a, c in zip(nums, cost))

low, high = min(nums), max(nums)
res = f(low)
while low < high:
mid = low + (high - low) // 2
y1, y2 = f(mid), f(mid + 1)
res = min(y1, y2)

if y1 < y2:
high = mid
else:
low = mid + 1

return res
15 changes: 15 additions & 0 deletions binary_search/test/test_min_cost.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import unittest

from binary_search.MinimumCostToMakeArrayEqual import min_cost


class MyTestCase(unittest.TestCase):
def test_min_cost(self):
self.assertEqual(8, min_cost(self, nums=[1, 3, 5, 2], cost=[2, 3, 1, 14]))

def test_min_cost_1(self):
self.assertEqual(0, min_cost(self, nums=[2, 2, 2, 2, 2], cost=[4, 2, 8, 1, 3]))


if __name__ == '__main__':
unittest.main()

0 comments on commit cacb0e1

Please sign in to comment.