문제
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.
정수 배열 번호와 정수 k가 제공됩니다.
0 < = i < nums.length인 각 인덱스 i에 대해 nums[i]를 nums[i] + k 또는 nums[i] - k로 변경합니다.
숫자의 점수는 숫자의 최대 요소와 최소 요소 간의 차이입니다.
각 인덱스에서 값을 변경한 후 최소 점수를 반환합니다.
예시
Example 1:
Input: nums = [1], k = 0
Output: 0
Explanation: The score is max(nums) - min(nums) = 1 - 1 = 0.
Example 2:
Input: nums = [0,10], k = 2
Output: 6
Explanation: Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6.
Example 3:
Input: nums = [1,3,6], k = 3
Output: 3
Explanation: Change nums to be [4, 6, 3]. The score is max(nums) - min(nums) = 6 - 3 = 3.
제약 조건
Constraints:
- 1 <= nums.length <= 104
- 0 <= nums[i] <= 104
- 0 <= k <= 104
해결 코드
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var smallestRangeII = function(nums, k) {
nums = nums.sort((a, b) => a - b);
let score = nums[nums.length - 1] - nums[0];
for(let i = 0 ; i < nums.length - 1 ; i++){
let min = Math.min(nums[0] + k, nums[i + 1] - k);
let max = Math.max(nums[nums.length - 1] - k, nums[i] + k);
score = Math.min(max - min, score);
}
return score;
};
'leetCode' 카테고리의 다른 글
[Medium] 143. Reorder List (0) | 2022.07.19 |
---|---|
[Medium] 304. Range Sum Query 2D - Immutable (0) | 2022.07.15 |
[Medium] 713. Subarray Product Less Than K (0) | 2022.07.07 |
[Medium] 438. Find All Anagrams in a String (0) | 2022.07.07 |
[Medium] 49. Group Anagrams (0) | 2022.07.06 |
Comment