2448.cpp (819B)
1 class Solution { 2 public: 3 long long minCost(const vector<int> &nums, const vector<int> &cost) { 4 const auto calc = [&const](int target) { 5 long long res = 0; 6 for (int i = 0; i < nums.size(); i++) 7 res += (long long)abs(nums[i] - target) * cost[i]; 8 return res; 9 }; 10 11 long left = 1L, right = 1000000L; 12 for (long num : nums) { 13 left = min(left, num); 14 right = max(right, num); 15 } 16 17 long ans = calc(1); 18 while (left < right) { 19 long mid = (left + right) / 2; 20 long y1 = calc(mid), y2 = calc(mid + 1); 21 ans = min(y1, y2); 22 if (y1 < y2) 23 right = mid; 24 else 25 left = mid + 1; 26 } 27 return ans; 28 } 29 };