-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feature: minimum cost to make array equal
- Loading branch information
1 parent
dd123ce
commit cacb0e1
Showing
2 changed files
with
39 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |