Skip to content

Latest commit

 

History

History
39 lines (33 loc) · 802 Bytes

908.最小差值-i.md

File metadata and controls

39 lines (33 loc) · 802 Bytes

908.最小差值-i

/*
 * @lc app=leetcode.cn id=908 lang=typescript
 *
 * [908] 最小差值 I
 */

// @lc code=start
function smallestRangeI(nums: number[], k: number): number {}
// @lc code=end

解法 1: 找最大最小值

function smallestRangeI(nums: number[], k: number): number {
  let max = -Infinity,
    min = Infinity
  for (let num of nums) {
    max = Math.max(max, num)
    min = Math.min(min, num)
  }
  return Math.max(0, max - k - (min + k))
}

Case

test.each([
  { input: { nums: [1], k: 0 }, output: 0 },
  { input: { nums: [0, 10], k: 2 }, output: 6 },
  { input: { nums: [1, 3, 6], k: 3 }, output: 0 },
])('input: nums = $input.nums, k = $input.k', ({ input: { nums, k }, output }) => {
  expect(smallestRangeI(nums, k)).toEqual(output)
})