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;
}
相关推荐
SZYSK1 小时前
鸿蒙人脸识别算法放在终端里:和外挂授权 SDK 差在排障路径
物联网·算法·华为·harmonyos
凯瑟琳.奥古斯特1 小时前
力扣1016高效解法:剪枝优化技巧
开发语言·c++·算法·leetcode·职场和发展
xiangyun612 小时前
C++ priority_queue 底层:手撕二叉堆与 Top K 问题
c++·算法·面试·stl·1024程序员节
qz_Serene3 小时前
练习算法题:双指针 -cpp
c++·算法·leetcode·1024程序员节
Nuanyt3 小时前
Hot 100 刷题笔记 · 数组与哈希专题(3 题)
java·笔记·算法·leetcode·哈希算法·1024程序员节
碧海银沙音频科技研究院3 小时前
基于炬芯平台ATS308X多模型兼容语音识别算法
人工智能·算法·语音识别
爱读书的小胖4 小时前
LeetCode 274 H 指数 C 语言解题分析
c语言·算法·leetcode·1024程序员节
basketball6164 小时前
动态规划第一章:引论
算法·动态规划·1024程序员节
星夜离尘564 小时前
MATLAB 因果采样保持:用历史匹配和数据年龄防止未来信息泄漏
数据结构·算法·matlab