Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Leetcode 2448. Minimum Cost to Make Array Equal #146

Open
Woodyiiiiiii opened this issue Oct 23, 2022 · 0 comments
Open

Leetcode 2448. Minimum Cost to Make Array Equal #146

Woodyiiiiiii opened this issue Oct 23, 2022 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

这道题一看就要用二分法,否则超时。

关键在于,往左往右的条件是什么?向哪边cost大呢?

一直没想到,其实题解在于,cost是一个凸函数,论证可以找下。但不妨这么想,以后实在想不到条件的,可以赌一把是不是凹函数还是凸函数

class Solution {
    public long minCost(int[] nums, int[] cost) {
        int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
        int costMaxI = 0, costMax = 0;
        for (int num : nums) {
            min = Math.min(min, num);
            max = Math.max(max, num);
        }

        long minSum = Long.MAX_VALUE;
        while (min <= max) {
            int mid = min + (max - min) / 2;
            long sum = getSum(nums, mid, cost);
            minSum = Math.min(minSum, sum);
            int midR = mid + 1;
            if (midR > max) {
                max = mid - 1;
            } else {
                long sumR = getSum(nums, midR, cost);
                if (sumR < sum) {
                    min = mid + 1;
                } else {
                    max = mid - 1;
                }
            }
        }

        return minSum;
    }
    
    private long getSum(int[] nums, int mid, int[] cost) {
        long sum = 0;
        for (int i = 0; i < nums.length; i++) {
            sum += (long) Math.abs(nums[i] - mid) * cost[i];
        }
        return sum;
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant