Program to find sum of medians of all odd length sublists in C++

C++Server Side ProgrammingProgramming

Suppose we have a list of numbers called nums, we have to find the sum of the medians of every odd−length sublist of the given list.

So, if the input is like nums = [2, 4, 6, 3], then the output will be 23, as the odd−length sublists are − [2], [4], [6], [3], [2, 4, 6], [4, 6, 3], so the sum of the medians is 2 + 4 + 6 + 3 + 4 + 4 = 23

To solve this, we will follow these steps −

  • ret := 0

  • for initialize i := 0, when i < size of nums, update (increase i by 1), do −

    • define priority queue called que_max

    • define another priority queue called que_min

    • for initialize j := i, when j < size of nums, update (increase j by 1), do −

      • insert nums[j] into que_max

      • while size of que_max >= 2, do −

        • insert top element of que_max into que_min

        • delete top element from que_max

      • while (size of que_min is not 0 and top element of que_max > top element of que_min), do −

        • a := top element of que_max, delete top element from que_max

        • b := top element of que_min, delete top element from que_min

        • insert b into que_max

        • insert a into que_min

      • if i mod 2 is same as j mod 2, then −

        • ret := ret + top element of que_max

  • return ret

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int solve(vector<int>& nums) {
   int ret = 0;
   for (int i = 0; i < nums.size(); i++) {
      priority_queue<int> que_max;
      priority_queue<int, vector<int>, greater<int>> que_min;
      for (int j = i; j < nums.size(); j++) {
         que_max.push(nums[j]);
         while (que_max.size() - que_min.size() >= 2) {
            que_min.push(que_max.top());
            que_max.pop();
         }
         while (que_min.size() && que_max.top() > que_min.top()) {
            int a = que_max.top();
            que_max.pop();
            int b = que_min.top();
            que_min.pop();
            que_max.push(b);
            que_min.push(a);
         }
         if (i % 2 == j % 2) {
            ret += que_max.top();
         }
      }
   }
   return ret;
}
int main(){
   vector<int> v = {2, 4, 6, 3};
   cout << solve(v);
}

Input

{2, 4, 6, 3}

Output

23
raja
Published on 25-Dec-2020 10:14:08
Advertisements