#1300
Sum of Mutated Array Closest to Target
MediumArrayBinary SearchSortingBinary SearchSorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
Instead of checking every possible value, we can use binary search on the possible values. The idea is to find the value that minimizes the absolute difference between the mutated sum and the target efficiently.
⚙️
Algorithm
5 steps- 1Step 1: Sort the array to allow binary search.
- 2Step 2: Use binary search to find the best value. Set low to 0 and high to the maximum value in arr.
- 3Step 3: For each mid value, calculate the mutated sum and check if it's less than or greater than the target.
- 4Step 4: Adjust the search range based on the comparison with the target.
- 5Step 5: After the search, check the closest values to determine the best one.
solution.py21 lines
1# Full working Python code
2
3def findBestValue(arr, target):
4 arr.sort()
5 low, high = 0, max(arr)
6
7 while low < high:
8 mid = (low + high) // 2
9 mutated_sum = sum(min(x, mid) for x in arr)
10 if mutated_sum < target:
11 low = mid + 1
12 else:
13 high = mid
14
15 # Check low and low-1 for the best value
16 mutated_sum_low = sum(min(x, low) for x in arr)
17 mutated_sum_low_minus_1 = sum(min(x, low - 1) for x in arr)
18 return low if abs(mutated_sum_low - target) < abs(mutated_sum_low_minus_1 - target) else low - 1
19
20# Example usage
21print(findBestValue([4,9,3], 10))ℹ
Complexity note: The sorting step takes O(n log n), and the binary search runs in O(log m) where m is the maximum value in arr, leading to an overall complexity of O(n log n).
- 1Understanding how mutation affects the sum is crucial.
- 2Binary search can significantly reduce the number of calculations needed.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.