Category: array-rearrange

Check if given array can be rearranged such that mean is equal to median

#include using namespace std;bool binarySearch(float arr[], int size, float key){    int low = 0, high = size – 1, mid;    while (low arr[mid])            low = mid + 1;                        else if (key < arr[mid])            high = mid - 1;                        else            return 1;    }            return 0;}bool twoPointers(float arr[], int N, float mean){    int i = 0, j = N - 1;    while (i < j) {                float temp = […]

Continue Reading

Rearrange Array to find K using Binary Search algorithm without sorting

#include using namespace std;  void Rearrange(int arr[], int K, int N){        int ans[N + 1];              int f = -1;      for (int i = 0; i < N; i++) {        ans[i] = -1;    }          K = find(arr, arr + N, K) – arr;                  vector smaller, greater;          for (int i = 0; i < N; i++) {                  if (arr[i] < arr[K])            smaller.push_back(arr[i]);                  else if (arr[i] > arr[K])            greater.push_back(arr[i]);    }      int low = […]

Continue Reading

Maximize average of the ratios of N pairs by M increments

  #include using namespace std;  double change(int pass, int total){    double currentPassRatio, newPassRatio;    double increase;          currentPassRatio = ((double)pass)                       / total;          newPassRatio = ((double)(pass + 1))                   / (total + 1);          increase = newPassRatio               – currentPassRatio;          return increase;}  double maximumAverage(    vector v, int M,    int N){        double sum = 0;      double increase, average;              priority_queue pq;    for (int i = 0; i < N; i++) {                          increase = change(v[i][0], v[i][1]);                          pq.push({ increase, i });                  average = v[i][0] * 1.0 […]

Continue Reading

Sort a permutation of first N Natural Numbers by swapping pairs satisfying given conditions

def Swap(x, y, p, posOfCurrNum):         posOfCurrNum[p[x]], posOfCurrNum[p[y]] = posOfCurrNum[p[y]], posOfCurrNum[p[x]]    p[x], p[y] = p[y], p[x]    return p, posOfCurrNumdef sortArray(p, n):                 posOfCurrNum = [0] * (n + 1)    for i in range(1, n + 1):        posOfCurrNum[p[i]] = i        ans = []        for i in range(1, n + 1):                                 if (p[i] == i):            continue                        j = posOfCurrNum[i]                        if (abs(i – j) * 2 >= n):            p, posOfCurrNum = Swap(i, j, […]

Continue Reading