The k Strongest Values in an Array in C++

C++Server Side ProgrammingProgramming

Suppose we have an array of numbers called arr and an integer k. There is a value arr[i] that is said to be stronger than a value arr[j] when |arr[i] - m| > |arr[j] - m| where m is the median of the array. If |arr[i] - m| is same as the |arr[j] - m|, then arr[i] is said to be stronger than arr[j] if arr[i] > arr[j]. So we have to find a list of the strongest k values in the array.

So, if the input is like arr = [1,2,3,4,5], k = 2, then the output will be [5,1], this is because median is 3, and the elements of the array sorted by the strongest are [5,1,4,2,3]. Here the strongest 2 elements are [5, 1]. [1, 5] is also valid. Although |5 - 3| is same as |1 - 3| but 5 is stronger than 1 because 5 > 1.

To solve this, we will follow these steps −

  • sort the array arr

  • n := size of arr

  • m := arr[(n - 1)/2]

  • Define an array v of pairs

  • i := 0, j := n - 1

  • Define an array ret

  • while k is non-zero, decrease k in each iteration, do −

    • x1 := |arr[j]- m|

    • x2 := |arr[i]- m|

    • if x1 >= x2, then −

      • insert arr[j] at the end of ret

      • (decrease j by 1)

    • Otherwise

      • insert arr[i] at the end of ret

      • (increase i by 1)

  • return ret

Example 

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<int> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Solution {
public:
   int calc(int x, int m){
      return abs(x - m);
   }
   vector<int> getStrongest(vector<int>& arr, int k) {
      sort(arr.begin(), arr.end());
      int n = arr.size();
      int m = arr[(n - 1) / 2];
      vector<pair<int, int> > v;
      int i = 0;
      int j = n - 1;
      vector<int> ret;
      while (k--) {
         int x1 = calc(arr[j], m);
         int x2 = calc(arr[i], m);
         if (x1 >= x2) {
            ret.push_back(arr[j]);
            j--;
         }
         else {
            ret.push_back(arr[i]);
            i++;
         }
      }
      return ret;
   }
};
main(){
   Solution ob;
   vector<int> v = {1,2,3,4,5};
   print_vector(ob.getStrongest(v,2));
}

Input

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

Output

[5, 1, ]
raja
Published on 18-Nov-2020 10:55:53
Advertisements