Minimum Range After Sum Operations Problem
Description
LeetCode Problem 4117.
You are given three integers a, b, and c.
You may perform the following operation any number of times (including zero):
- Choose one of the three integers and replace it with the sum of the other two integers. The other two integers remain unchanged.
The range of three integers is defined as the difference between the maximum value and the minimum value.
Return the minimum range that can be obtained after performing the operation any number of times.
Example 1:
Input: a = 9, b = 2, c = 5
Output: 5
Explanation:
One sequence of operations which results in the minimum range is as follows:
- Set a to b + c = 2 + 5 = 7. The three integers are now a = 7, b = 2, c = 5.
- The range of the three integers is max(7, 2, 5) - min(7, 2, 5) = 7 - 2 = 5.
Example 2:
Input: a = 5, b = 7, c = 6
Output: 2
Explanation:
Without doing any operations, the range of the three integers is max(5, 7, 6) - min(5, 7, 6) = 7 - 5 = 2.
Example 3:
Input: a = 3, b = 3, c = 3
Output: 0
Explanation:
Without doing any operations, the range of the three integers is max(3, 3, 3) - min(3, 3, 3) = 3 - 3 = 0.
Constraints:
1 <= a, b, c <= 100
Solution
Approach: Sorting
Sort the three numbers so that nums[0] <= nums[1] <= nums[2]. With no operation the range is nums[2] - nums[0].
All numbers are positive, so an operation replaces one number by something at least as large as each of the two that stay. That means the minimum never decreases, and the range can only shrink if the maximum is the number being replaced. After replacing the maximum, the numbers are nums[0], nums[1] and nums[0] + nums[1]. If the new sum is still at least nums[2], the maximum is now larger, and going on only makes the range bigger. If the sum is below nums[2], the new maximum is nums[1] or the sum itself, and the best the range gets is nums[1]. Replacing the smallest or the middle number creates a value larger than the old maximum, which does not help.
So the answer is min(nums[2] - nums[0], nums[1]).
Complexity: O(1) time and O(1) extra space.
class Solution:
def minRange(self, a: int, b: int, c: int) -> int:
nums = [a, b, c]
nums.sort()
return min(nums[2] - nums[0], nums[1])