
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Smallest Range II in C++
Suppose we have an array A of integers, for each integer A[i] we have to choose either x = -K or x = K, and add x to A[i] (only once). So after this process, we have some array B. We have to find the smallest possible difference between the maximum value of B and the minimum value of B. So if the input is A = [0,10], K = 2, then the output will be 6, as B = [2,8].
To solve this, we will follow these steps −
set ret := 0, n := size of array A
sort the array A
set ret := Last element of A – first element of A
right := Last element of A – K and left := first element of A + k
-
for i in range 0 to n – 1
mx := max of A[i] + k and right
mn := min of A[i + 1] – k and left
ret := min of ret and (mx - min)
return ret
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class Solution { public: int smallestRangeII(vector<int>& A, int k) { int ret = 0; int n = A.size(); sort(A.begin(), A.end()); ret = A[n - 1] - A[0]; int mx, mn; int right = A[n - 1] - k; int left = A[0] + k; for(int i = 0; i < n - 1; i++){ mx = max(A[i] + k, right); mn = min(A[i + 1] - k, left); ret = min(ret, mx - mn); } return ret; } }; main(){ vector<int> v = {0, 10}; Solution ob; cout << (ob.smallestRangeII(v, 2)); }
Input
[0,10] 2
Output
6