LeetCode1300. 转变数组后最接近目标值的数组和 [Medium]

1300. Sum of Mutated Array Closest to Target

Given an integer array arr and a target value target, return the integer value such that when we change all the integers larger than value in the given array to be equal to value, the sum of the array gets as close as possible (in absolute difference) to target.

In case of a tie, return the minimum such integer.

Notice that the answer is not neccesarilly a number from arr.

Example 1:

Input: arr = [4,9,3], target = 10
Output: 3
Explanation: When using 3 arr converts to [3, 3, 3] which sums 9 and that's the optimal answer.

Example 2:

Input: arr = [2,3,5], target = 10
Output: 5

Example 3:

Input: arr = [60864,25176,27249,21296,20204], target = 56803
Output: 11361

Constraints:

  • 1 <= arr.length <= 10^4
  • 1 <= arr[i], target <= 10^5

题目:给你一个整数数组 arr 和一个目标值 target ,请你返回一个整数 value ,使得将数组中所有大于 value 的值变成 value 后,数组的和最接近 target (最接近表示两者之差的绝对值最小)。如果有多种使得和最接近 target 的方案,请你返回这些整数中的最小值。请注意,答案不一定是 arr 中的数字。

思路:参考lee215。因为需要找到一个pivot值,将大于等于pivot的值替换为pivot后,使得整个数组的和最接近target。因此首先对数组进行排序,在位置i时,如果arr[i] * (n-i)的值大于target,说明仍可以增大pivot的值,更新pivot的位置,在右移的过程中同时更新target的值。

工程代码下载

class Solution {
public:
    int findBestValue(vector<int>& arr, int target) {
        sort(arr.begin(), arr.end());
        int n = arr.size(), i = 0;
        while(i < n && target > arr[i] * (n-i))
            target -= arr[i++];
        // 减0.0001是为了在出现多种解时,取结果小的,如arr=[4, 9, 3], target=10
        return i == n ? arr[n-1] : round((target-0.0001) / (n-i));
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值