Leetcode 910: Smallest Range II

grid47
grid47
Exploring patterns and algorithms
Aug 8, 2024 6 min read

You are given an integer array nums and an integer k. For each element in nums, you can either add or subtract k. The score of the array is calculated as the difference between the maximum and minimum elements of the modified array. Your task is to find and return the minimum possible score after modifying the values in the array.
Problem
Approach
Steps
Complexity
Input: The input consists of an integer array `nums` and an integer `k`.
Example: Input: nums = [5, 8], k = 3
Constraints:
• 1 <= nums.length <= 10^4
• 0 <= nums[i] <= 10^4
• 0 <= k <= 10^4
Output: Return the minimum score of the array after modifying the values of the elements.
Example: Output: 4
Constraints:
• The returned score should be the smallest possible score after modifying the array.
Goal: The goal is to minimize the score of the array by appropriately modifying each element with either addition or subtraction of `k`.
Steps:
• Sort the input array `nums` to arrange the elements in ascending order.
• Initialize the left boundary as `nums[0] + k` and the right boundary as `nums[n-1] - k`.
• Iterate through the sorted array and compute the new score by adjusting each element by either adding or subtracting `k`.
• Track the minimum score by updating the result after each modification.
Goal: The constraints limit the size of the array and the range of possible values for the elements and `k`.
Steps:
• The length of the array is between 1 and 10^4.
• Each element of the array is between 0 and 10^4.
• The value of `k` is between 0 and 10^4.
Assumptions:
• The array is non-empty, with at least one element.
Input: Input: nums = [5, 8], k = 3
Explanation: In this case, changing the values of `5` and `8` by adding or subtracting `3` gives [2, 11]. The score is the difference between the maximum and minimum, which is 11 - 2 = 9.

Input: Input: nums = [2, 4, 7], k = 1
Explanation: Here, changing the values of `2`, `4`, and `7` results in [3, 3, 6]. The score is the difference between the maximum and minimum, which is 6 - 3 = 3.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus