Leetcode 1232 Solution

This article provides solution to leetcode question 1232 (sum-of-mutated-array-closest-to-target)

https://leetcode.com/problems/sum-of-mutated-array-closest-to-target

Solution

class Solution:
    def findBestValue(self, arr: List[int], target: int) -> int:
        arr.sort()

        value = 1
        curr_sum = 0

        opt = 0
        ans = 0

        i = 0
        while value <= 100000:
            while i < len(arr) and value > arr[i]:
                curr_sum += arr[i]
                i += 1

            if i == len(arr):
                break

            total = curr_sum + value * (len(arr) - i)

            if abs(total - target) < abs(opt - target):
                opt = total
                ans = value

            value += 1

        return ans