Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Smallest Range I in Python
The Smallest Range I problem asks us to find the minimum possible difference between the maximum and minimum values of an array after we're allowed to add any value between -K and K to each element.
Given an array A of integers, for each integer A[i] we can choose any x with range [-K, K] and add x to A[i]. After this process, we get array B. We need to find the smallest possible difference between the maximum and minimum values of B.
Problem Understanding
Let's understand this with an example. If A = [0, 10] and K = 2:
- For A[0] = 0, we can add any value from [-2, 2], so it becomes [?2, 2]
- For A[1] = 10, we can add any value from [-2, 2], so it becomes [8, 12]
- To minimize the range, we want the maximum value as small as possible and minimum value as large as possible
- Best strategy: make A[0] = 0 + 2 = 2 and A[1] = 10 ? 2 = 8
- So B = [2, 8] and the difference is 8 ? 2 = 6
Algorithm
To minimize the range, we should:
- Increase the minimum element by K (to make it as large as possible)
- Decrease the maximum element by K (to make it as small as possible)
The steps are:
- MAX := (maximum of A) ? K
- MIN := (minimum of A) + K
- difference := MAX ? MIN
- If difference < 0, return 0 (elements can overlap)
- Otherwise return difference
Implementation
class Solution:
def smallestRangeI(self, A, K):
MAX = max(A) - K
MIN = min(A) + K
difference = MAX - MIN
if difference < 0:
return 0
else:
return difference
# Test the solution
ob = Solution()
print(ob.smallestRangeI([0, 10], 2))
print(ob.smallestRangeI([1, 3, 6], 3))
6 0
How It Works
The algorithm works by finding the optimal adjustment strategy:
- Original range: max(A) ? min(A)
- After adjustment: (max(A) ? K) ? (min(A) + K) = max(A) ? min(A) ? 2K
- If this becomes negative, it means all elements can be made equal, so the minimum range is 0
Examples
Example 1
# A = [0, 10], K = 2
A = [0, 10]
K = 2
solution = Solution()
result = solution.smallestRangeI(A, K)
print(f"Input: A = {A}, K = {K}")
print(f"Output: {result}")
Input: A = [0, 10], K = 2 Output: 6
Example 2
# A = [1, 3, 6], K = 3
A = [1, 3, 6]
K = 3
solution = Solution()
result = solution.smallestRangeI(A, K)
print(f"Input: A = {A}, K = {K}")
print(f"Output: {result}")
print(f"Explanation: min=1+3=4, max=6-3=3, difference=3-4=-1, so return 0")
Input: A = [1, 3, 6], K = 3 Output: 0 Explanation: min=1+3=4, max=6-3=3, difference=3-4=-1, so return 0
Conclusion
The Smallest Range I problem is solved by adjusting the minimum element upward by K and the maximum element downward by K. If the resulting range becomes negative, all elements can overlap, giving a minimum range of 0.
