C++ Program to find out the least amount of money required to subscribe to the OTT services



Suppose, a telecom operator has introduced a service called "all-in-one" which provides access to n OTT content providers at a fixed price of k dollars. Now, if we have to subscribe to the OTT platforms directly, we have to pay an individual amount of fee to each of the platforms. We do not need subscriptions to every platform at all months, so we have to find a way to cost-effectively use their services. The starting month in which we need the service of platform i is given in the array start_month and the ending month is given in the array end_month. The price needed to subscribe to a platform is given in the array price[i]. We have to find out the least amount of money we have to pay to subscribe to all the platforms as per our requirement.

So, if the input is like n = 3, k = 10, start_month = {1, 2, 1}, end_month = {3, 3, 2}, price = {5, 7, 8}, then the output will be 30

We need a subscription to the services for 3 months.

In the first month, we need subscriptions for platforms 1 and 3. Individually, they cost a total of 5 + 8 = 13 dollars, but with the "all-in-one" package it costs 10 dollars only. Similarly in the second month, we need all three which costs 20 dollars in total. But we pay 10 for all three. And in the third month, the total cost for the subscriptions becomes 12 dollars, but we pay only 10.

So, the total cost is 10 + 10 + 10 = 30.

Steps

To solve this, we will follow these steps −

Define an array pairArray
for initialize i := 0, when i < n, update (increase i by 1), do:
   insert pair(start_month[i], price[i]) at the end of pairArray
   insert pair(end_month[i] + 1, -price[i]) at the end of pairArray
sort the array pairArray
pre := 0
c := 0
res := 0
for each element p in pairArray, do:
   day := first element of p - pre
   res := res + minimum of (k, c)
   c := c + second element of p
pre := first element of p
return res

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;

vector<vector<int>> G;
vector<int> res;

int solve(int n, int k, int start_month[], int end_month[], int price[]){
   vector<pair<int, int>> pairArray;
   for(int i = 0; i < n; i++) {
      pairArray.push_back(make_pair(start_month[i], price[i]));
      pairArray.push_back(make_pair(end_month[i] + 1, -price[i]));
   }
   sort(pairArray.begin(), pairArray.end());
   int pre = 0;
   int c = 0;
   int res = 0;
   for(auto p : pairArray) {
      int day = p.first - pre;
      res += min(k, c) * day;
      c += p.second; pre = p.first;
   }
   return res;
}
int main() {
   int n = 3, k = 10, start_month[] = {1, 2, 1}, end_month[] = {3, 3, 2}, price[] = {5, 7, 8};
   cout<< solve(n, k, start_month, end_month, price);
   return 0;
}

Input

3, 10, {1, 2, 1}, {3, 3, 2}, {5, 7, 8}

Output

30

Advertisements