Algorithm


Problem Name: 908. Smallest Range I

You are given an integer array nums and an integer k.

In one operation, you can choose any index i where 0 <= i < nums.length and change nums[i] to nums[i] + x where x is an integer from the range [-k, k]. You can apply this operation at most once for each index i.

The score of nums is the difference between the maximum and minimum elements in nums.

Return the minimum score of nums after applying the mentioned operation at most once for each index in it.

 

Example 1:

Input: nums = [1], k = 0
Output: 0
Explanation: The score is max(nums) - min(nums) = 1 - 1 = 0.

Example 2:

Input: nums = [0,10], k = 2
Output: 6
Explanation: Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6.

Example 3:

Input: nums = [1,3,6], k = 3
Output: 0
Explanation: Change nums to be [4, 4, 4]. The score is max(nums) - min(nums) = 4 - 4 = 0.

 

Constraints:

  • 1 <= nums.length <= 104
  • 0 <= nums[i] <= 104
  • 0 <= k <= 104

Code Examples

#1 Code Example with Java Programming

Code - Java Programming


class Solution {
  public int smallestRangeI(int[] A, int K) {
    int maximum = A[0];
    int minimum = A[0];
    for (int num : A) {
      maximum = Math.max(num, maximum);
      minimum = Math.min(num, minimum);
    }
    return Math.max(0, maximum - minimum - 2 * K); 
  }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
nums = [1], k = 0

#2 Code Example with Javascript Programming

Code - Javascript Programming


const smallestRangeI = function(nums, k) {
  let min = Infinity, max = -Infinity
  for(let e of nums) {
    min = Math.min(min, e)
    max = Math.max(max, e)
  }
  return max - k >= min + k ? max - k - (min + k) : 0
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
nums = [1], k = 0

#3 Code Example with Python Programming

Code - Python Programming


class Solution:
    def smallestRangeI(self, A, K):
        l, r = min(A) + K, max(A) - K 
        return 0 if l >= r else r - l
Copy The Code & Try With Live Editor

Input

x
+
cmd
nums = [0,10], k = 2

Output

x
+
cmd
6

#4 Code Example with C# Programming

Code - C# Programming


using System;

namespace LeetCode
{
    public class _0908_SmallestRangeI
    {
        public int SmallestRangeI(int[] A, int K)
        {
            int max = int.MinValue, min = int.MaxValue;
            foreach (var num in A)
            {
                max = Math.Max(num, max);
                min = Math.Min(num, min);
            }

            var result = max - min - K * 2;
            return result  <  0 ? 0 : result;
        }
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
nums = [0,10], k = 2

Output

x
+
cmd
6
Advertisements

Demonstration


Previous
#907 Leetcode Sum of Subarray Minimums Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#909 Leetcode Snakes and Ladders Solution in C, C++, Java, JavaScript, Python, C# Leetcode