LeetCode //C - 1300. Sum of Mutated Array Closest to Target

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 < = a r r . l e n g t h < = 10 4 1 <= arr.length <= 10^4 1<=arr.length<=104
  • 1 < = a r r i , t a r g e t < = 10 5 1 <= arri, target <= 10^5 1<=arri,target<=105

From: LeetCode

Link: 1300. Sum of Mutated Array Closest to Target


Solution:

Ideas:

Binary search the smallest value whose mutated array sum is at least target, then compare it with the previous value.

Code:
c 复制代码
#include <stdlib.h>

int findBestValue(int* arr, int arrSize, int target) {
    int left = 0;
    int right = 0;

    for (int i = 0; i < arrSize; i++) {
        if (arr[i] > right) {
            right = arr[i];
        }
    }

    while (left < right) {
        int mid = left + (right - left) / 2;
        int sum = 0;

        for (int i = 0; i < arrSize; i++) {
            sum += arr[i] < mid ? arr[i] : mid;
        }

        if (sum < target) {
            left = mid + 1;
        } else {
            right = mid;
        }
    }

    int sum1 = 0;
    int sum2 = 0;

    for (int i = 0; i < arrSize; i++) {
        sum1 += arr[i] < left ? arr[i] : left;
        sum2 += arr[i] < left - 1 ? arr[i] : left - 1;
    }

    if (abs(sum2 - target) <= abs(sum1 - target)) {
        return left - 1;
    }

    return left;
}
相关推荐
逐米时代2 小时前
「制造新解法」行业对标方法:借鉴而不照搬的最佳实践
人工智能·算法·制造
kyrie_sakura3 小时前
大模型学习32 --大模型微调3 -- 分布式训练算法
分布式·学习·算法
Rabitebla3 小时前
【Linux】 文件系统(五):挂载与软硬链接,多个文件系统怎样组成统一目录树
linux·运维·服务器·c++·笔记·学习·算法
m0_743106464 小时前
SAD-GS:从梯度邻域到频率驱动表达3D空间
人工智能·算法·计算机视觉·3d·几何学
csdn_aspnet4 小时前
Java 使总距离最短的最佳点位置(Optimum location of point to minimize total distance)
java·算法
专注仿真5 小时前
仿真智能体训练(评估指标篇):任务完成率算法详解与实战
人工智能·算法·机器学习·afsim智能体·仿真训练·afsim智能体训练·任务完成率算法
小手cool6 小时前
二分查找:在有序数组中查找最接近 target 的元素索引
java·数据结构·算法
zmzb01036 小时前
C++课后习题训练记录Day216
数据结构·c++·算法
INGNIGHT6 小时前
leetcode尊享100题
算法·哈希算法
做cv的小昊8 小时前
【大模型算法自学笔记07】NLP基础知识(1.7 Embedding)
人工智能·笔记·算法·计算机视觉·自然语言处理·transformer·embedding