C++ Program to find minimum difference between strongest and weakest


Suppose we have an array A with n elements. There are n athletes in a game. They are numbered from 1 to n and arranged in left to right order. The strength of each athlete i is A[i]. We want to split all athletes into two teams. Each team must have at least one athlete, and each athlete must be exactly in one team. We want the strongest athlete from the first team to differ as little as possible from the weakest athlete from the second team. We have to find the minimum difference between their strength as mentioned above.

Problem Category

The above-mentioned problem can be solved by applying Greedy problem-solving techniques. The greedy algorithm techniques are types of algorithms where the current best solution is chosen instead of going through all possible solutions. Greedy algorithm techniques are also used to solve optimization problems, like its bigger brother dynamic programming. In dynamic programming, it is necessary to go through all possible subproblems to find out the optimal solution, but there is a drawback of it; that it takes more time and space. So, in various scenarios greedy technique is used to find out an optimal solution to a problem. Though it does not gives an optimal solution in all cases, if designed carefully it can yield a solution faster than a dynamic programming problem. Greedy techniques provide a locally optimal solution to an optimization problem. Examples of this technique include Kruskal's and Prim's Minimal Spanning Tree (MST) algorithm, Huffman Tree coding, Dijkstra's Single Source Shortest Path problem, etc.

https://www.tutorialspoint.com/data_structures_algorithms/greedy_algorithms.htm

https://www.tutorialspoint.com/data_structures_algorithms/dynamic_programming.htm

So, if the input of our problem is like A = [2, 1, 3, 2, 4, 3], then the output will be 0, because one of the optimal splits are, T1 = [2, 1] and T2 = [3, 2, 4, 3], so |2 - 2| = 0.

Steps

To solve this, we will follow these steps −

n := size of A
sort the array A
ans := 1000
for initialize i := 1, when i < n, update (increase i by 1), do:
   ans := minimum of ans and A[i] - A[i - 1]
return ans

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
int solve(vector<int> A){
   int n = A.size();
   sort(A.begin(), A.end());
   int ans = 1000;
   for (int i = 1; i < n; ++i){
      ans = min(ans, A[i] - A[i - 1]);
   }
   return ans;
}
int main(){
   vector<int> A = { 2, 1, 3, 2, 4, 3 };
   cout << solve(A) << endl;
}

Input

{ 2, 1, 3, 2, 4, 3 }

Output

0

Updated on: 07-Apr-2022

112 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements