DDSA Solutions

908. Smallest Range I

Time: O(n)
Space: O(1)
Advertisement

Intuition

Each element can shift by at most k. Minimum possible score = max(0, max-min-2k).

Algorithm

  1. 1Return max(0, max(A) - min(A) - 2*k).

Common Pitfalls

  • Result cannot be negative.
908.cs
C#
// Approach: Range only narrows if the gap between max and min exceeds 2k; answer is max(0, max - min - 2k).
// Time: O(n) Space: O(1)

public class Solution
{
    public int SmallestRangeI(int[] nums, int k)
    {
        int mx = nums.Max();
        int mn = nums.Min();
        return Math.Max(0, mx - mn - 2 * k);
    }
}
Advertisement
Was this solution helpful?