LeetCode 910. Smallest Range II
考点 | 难度 |
---|---|
Greedy | Easy |
题目
You are given an integer array nums and an integer k.
For each index i where 0 <= i < nums.length, change nums[i] to be either nums[i] + k or nums[i] - k.
The score of nums is the difference between the maximum and minimum elements in nums.
Return the minimum score of nums after changing the values at each index.
思路
首先从小到大sort array。trivial case是所有数一起increase或者decrease k,先记录这个差(array里的最大-array里的最小)为score。把array分成两段,前一段+k后一段-k,两段的maximum分别是第一段max+k和第二段max-k,两段的minimum分别是第一段min+k和第二段max+k。算差,和score比较。
答案
class Solution:
def smallestRangeII(self, nums, k):
N = len(nums)
nums.sort()
score = nums[-1] - nums[0]
# To store minimum score
ans = score
# Check all N-1 Non-Trivial partitions/walls.
# Both sets will be non-empty
for divider in range(0, N-1):
# Compute maximum and minimum after partitioning
# Kudos! We only have two candidates for each
maximumAfterDivision = max(nums[divider] + k , nums[-1] - k)
minimumAfterDivision = min(nums[divider+1] - k , nums[0] + k)
# Score after dividing here
score = maximumAfterDivision - minimumAfterDivision
# ans will be minimum score
ans = min(ans, score)
# return answer
return ans