
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
Find Minimum Possible Number of Keyboards Stolen in C++
Suppose we have an array A with n elements. There was an electronic store, where a robbery has done on the last night. All keyboards which were present inside the store were numbered in ascending order from some integer number x. For example, for x=4 and there were 3 keyboards in the store, then the devices had indices 4, 5 and 6. If x=10 and there were 7 of them then the keyboards had indices 10, 11, 12, 13, 14, 15 and 16. After the robbery, only n keyboards are left. They have indices stored in array A. We have to find the minimum possible number of keyboards that have been stolen.
So, if the input is like A = [10, 13, 12, 8], then the output will be 2, because if x = 8 then minimum number of stolen keyboards is 2. The keyboards with indices 9 and 11 were stolen.
Steps
To solve this, we will follow these steps −
sort the array A n := size of A return A[n - 1] - A[0] + 1 - n
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; int solve(vector<int> A) { sort(A.begin(), A.end()); int n = A.size(); return A[n - 1] - A[0] + 1 - n; } int main() { vector<int> A = { 10, 13, 12, 8 }; cout << solve(A) << endl; }
Input
{ 10, 13, 12, 8 }
Output
2