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;
}
相关推荐
another heaven7 小时前
【C/C++ Ranges 是零开销抽象吗?拆开管道、惰性求值和编译期膨胀】
c语言·开发语言·c++
Code_Solitude7 小时前
C语言动态内存 + 柔性数组 + 数组名退化
c语言·算法·柔性数组
上海潭龙东海科技有限公司7 小时前
客运站管控之动态孪生技术方案(新增一屏管控模块
数据仓库·人工智能·算法·重构·动态规划
文丑颜不良啊8 小时前
LeetCode2821~2840题目解析
java·leetcode
YLCHUP9 小时前
【思维&图论建模】题解:债权(debt)_图论_建模_思路转化_思维题目_C++算法竞赛
c++·笔记·算法·数学建模·贪心算法·深度优先·图论
思麟呀10 小时前
背包DP(01背包+完全背包)
c++·算法
Zwawa11 小时前
让屏幕动起来:OLED动画效果,丝滑光标、帧动画和一只贪吃蛇
c语言·单片机·嵌入式
笑容掩饰我的失落11 小时前
区块链从小白到精通(七):Solidity 语法精讲——数据类型、函数、修饰器与事件
算法·区块链·php·智能合约·哈希算法
Pniubi12 小时前
力扣24. 两两交换链表中的节点(递归)
算法·leetcode·链表