Given an array
After this process, we have some array
Return the smallest possible difference between the maximum value of
A
of integers, for each integer A[i]
we may choose any x
with -K <= x <= K
, and add x
to A[i]
.After this process, we have some array
B
.Return the smallest possible difference between the maximum value of
B
and the minimum value of B
.Example 1:
Input: A = [0,10], K = 2
Output: 6
Explanation: B = [2,8]
Approach
Java
import java.util.Arrays;public class SmallestRangeI {public static void main(String[] args) {int[] A = { 0, 10 };int K = 2;System.out.println(smallestRangeI(A, K));}static int smallestRangeI(int[] A, int K) {Arrays.sort(A);int n = A.length;int x = A[n - 1] - A[0];if (x / 2 < K)return 0;return A[n - 1] - A[0] - 2 * K;}}
C++
#include <bits/stdc++.h>using namespace std;int smallestRangeI(vector<int> &A, int K){sort(A.begin(), A.end());int n = A.size();int x = A[n - 1] - A[0];if (x / 2 < K)return 0;return A[n - 1] - A[0] - 2 * K;}int main(){vector<int> A = {0, 10};int K = 2;cout << smallestRangeI(A, K);return 0;}
No comments:
Post a Comment