#908

Smallest Range I

Easy
ArrayMathArrayMath
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution leverages the fact that we can adjust the maximum and minimum values directly. Instead of brute-forcing through combinations, we can compute the new boundaries based on the maximum and minimum values in the array.

⚙️

Algorithm

3 steps
  1. 1Step 1: Find the maximum and minimum values in the array.
  2. 2Step 2: Calculate the potential new maximum as max(nums) - k and the new minimum as min(nums) + k.
  3. 3Step 3: The minimum score will be the difference between the new maximum and new minimum, ensuring it does not go below zero.
solution.py7 lines
1# Full working Python code
2
3def smallestRangeI(nums, k):
4    return max(0, max(nums) - min(nums) - 2 * k)
5
6# Example usage
7print(smallestRangeI([1, 3, 6], 3))  # Output: 0

Complexity note: The time complexity is O(n) because we only traverse the array once to find the max and min values. The space complexity is O(1) since we are using a constant amount of extra space.

  • 1Adjusting the max and min values directly minimizes the score.
  • 2The score cannot be negative, so we return 0 if the calculated score is negative.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.