Leetcode 910. Smallest Range II
The problem is defined on LeetCode as follows:
You are given an integer array A
and an integer K
. For each integer in the array, you can choose to add K
to it or subtract K
from it.
Return the smallest possible difference between the maximum value and the minimum value of the array after performing up to one of these operations on each array element.
Example:
Input: A = [1, 3, 6], K = 3
Output: 3
Explanation: Choose (1+3), (3+3), (6-3). The resulting array is [4, 6, 3] and the difference between the max and min is 6-3 = 3.
A
and K
?
A
will be between 1
and 10000
.A
can be as large as 10^5
in absolute value.K
is a non-negative integer less than or equal to 10^4
.K
is added or subtracted.K
to each element.low
and high
) formed by the middle elements and their potential shifted values.#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
int smallestRangeII(std::vector<int>& A, int K) {
if (A.size() == 1) {
return 0; // If there's only one element, no range calculation is needed.
}
std::sort(A.begin(), A.end());
int n = A.size();
int initialRange = A[n - 1] - A[0];
int result = initialRange;
for (int i = 0; i < n - 1; ++i) {
int high = std::max(A[n - 1] - K, A[i] + K);
int low = std::min(A[0] + K, A[i + 1] - K);
result = std::min(result, high - low);
}
return result;
}
int main() {
std::vector<int> A = {1, 3, 6};
int K = 3;
std::cout << "Smallest Range II: " << smallestRangeII(A, K) << std::endl;
return 0;
}
O(n log n)
where n
is the length of the array A
.O(n)
as it involves a single pass through the array.Hence, the total time complexity is O(n log n)
, dominated by the sorting step.
This approach ensures that we attempt to minimize the difference effectively, considering all possible adjustments with given constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?