910. 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:
Example 2:
Example 3:
Note:
1 <= A.length <= 10000
0 <= A[i] <= 10000
0 <= K <= 10000
Thoughts
对给定数组每个元素可选+K或-K,问选择后argmin(最大值-最小值)。最大和最小=>sorting:从小到大排序,右边那头往下压,左边的往上提,从而使得最大和最小之间的差最小。假设A[i]是左边往上提的最右边的元素,最大值可能是A[i] + K或A[-1] - K,那最小值可能是A[i + 1] - K或A[0] + K。遍历所有的i看全局最优。
Code
Analysis
时间复杂度O(nlgn)
Last updated
Was this helpful?