leetcode 1300

转变数组后最接近目标值的数组和

Posted by Static on June 14, 2020

题目链接:https://leetcode-cn.com/problems/sum-of-mutated-array-closest-to-target/

题目描述


分析

1. 优化循环


代码实现

public enum Q1300 {
    instance;

    // result 不一定是arr中的数字
    public int findBestValue(int[] arr, int target) {
        int big = 0;
        int sum = 0;
        for (int i : arr) {
            sum += i;
            big = big > i ? big : i;
        }
        if (sum <= target) return big;
        int ans = target / arr.length;
        sum = getSum(arr, ans);
        while (sum < target) {
            int sumn = getSum(arr, ans + 1);
            if (sumn >= target) return target - sum <= sumn - target ? ans : ans + 1;
            sum = sumn;
            ans++;
        }
        return 0;
    }

    public int getSum(int[] arr, int value) {
        int sum = 0;
        for (int i : arr) sum += i < value ? i : value;
        return sum;
    }

    public static void main(String[] args) {
        // assert 3
        System.out.println(Q1300.instance.findBestValue(new int[]{4, 9, 3}, 10));
        // assert 5
        System.out.println(Q1300.instance.findBestValue(new int[]{2,3,5},10));
        // assert 11361
        System.out.println(Q1300.instance.findBestValue(new int[]{60864,25176,27249,21296,20204},56803));
    }
}