Leetcode - Smallest Range II
https://leetcode.com/problems/smallest-range-ii/
Given an array A
of integers, for each integer A[i]
we need to choose either x = -K
or x = K
, and add x
to A[i] (only once)
.
After this process, we have some array B
.
Return the smallest possible difference between the maximum value of B
and the minimum value of B
.
Example 1:
Input: A = [1], K = 0 Output: 0 Explanation: B = [1]
Example 2:
Input: A = [0,10], K = 2 Output: 6 Explanation: B = [2,8]
func smallestRangeII(A []int, K int) int { sort.Ints(A) result := A[len(A)-1] - A[0] for i := 0; i < len(A)-1; i++ { a := A[i] b := A[i+1] high := max(A[len(A)-1] - K, a + K) low := min(A[0] + K, b - K) result = min(result, high - low) } return result } func min(a, b int) int{ if a < b { return a } return b } func max(a, b int) int { if a > b { return a } return b }