
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- Smallest Range I in Python
- Range Addition II in C++
- Smallest Range Covering Elements from K Lists in C++
- Count number of smallest elements in given range in C++
- Find smallest range containing elements from k lists in C++
- kth smallest/largest in a small range unsorted array in C++
- Count all the numbers in a range with smallest factor as K in C++
- Find kth smallest number in range [1, n] when all the odd numbers are deleted in C++
- Range Overflow and Range Underflow properties in JavaScript.
- Find the smallest and second smallest elements in an array in C++
- Maximum sum of smallest and second smallest in an array in C++
- Maximum sum of smallest and second smallest in an array in C++ Program
- Program to find kth smallest n length lexicographically smallest string in python
- Binary Indexed Tree: Range Update and Range Queries in C++
- Smallest Good Base in Python
