![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ program to find indices of soldiers who can form reconnaissance unit
Suppose we have an array A with n elements. There are n soldiers standing on a circle. For ith soldier, the height is A[i]. A reconnaissance unit can be made of such two adjacent soldiers, whose heights difference is minimal. So each of them will be less noticeable with the other. We have to find the indices of the pair of soldiers that can form a reconnaissance unit.
So, if the input is like A = [10, 12, 13, 15, 10], then the output will be (5, 1).
Steps
To solve this, we will follow these steps −
n := size of A D := |A[0] - A[n - 1]| H := n for initialize i := 1, when i < n, update (increase i by 1), do: if D > |A[i] - A[i - 1]|, then: D := |A[i] - A[i - 1]| H := i print H and (H mod n)
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; void solve(vector<int> A) { int n = A.size(); int D = abs(A[0] - A[n - 1]); int H = n; for (int i = 1; i < n; i++) { if (D > abs(A[i] - A[i - 1])) { D = abs(A[i] - A[i - 1]); H = i; } } cout << H << ", " << (H % n) + 1; } int main() { vector<int> A = { 10, 12, 13, 15, 10 }; solve(A); }
Input
{ 10, 12, 13, 15, 10 }
Output
5, 1
Advertisements