TV Shows in C++


Suppose we have a list of TV shows, and another list of duration, and an integer k, here shows[i] and duration[i] shows the name and duration watched by the ith person, we have to find the total duration watched of the k most watched shows.

So, if the input is like shows: ["Castle Play", "Fairy Tale Series", "Castle Play", "Jerry Mouse", "Rich Boy"], duration: [6, 4, 6, 14, 5] and k = 2, then the output will be 26.

To solve this, we will follow these steps −

  • Define one map m

  • n := size of v

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

    • m[v[i]] := m[v[i]] + d[i]

  • define an array arr

  • for each key-value pair it of m

    • insert value of it at the end of arr

  • sort the array arr in reverse order

  • ret := 0

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

    • ret := ret + arr[i]

  • return ret

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int solve(vector<string>& v, vector<int>& d, int k) {
      map <string, int> m;
      int n = v.size();
      for(int i = 0; i < n; i++){
         m[v[i]] += d[i];
      }
      vector < int > arr;
      for(auto it : m){
         arr.push_back(it.second);
      }
      sort(arr.rbegin(), arr.rend());
      int ret = 0;
      for(int i = 0; i < k; i++){
         ret += arr[i];
      }
      return ret;
   }
};
int main(){
   vector<string> v = {"Castle Play", "Fairy Tale Series", "Castle
   Play", "Jerry Mouse", "Rich Boy"};
   vector<int> v1 = {6, 4, 6, 14, 5};
   Solution ob;
   cout << (ob.solve(v, v1, 2));
}

Input

{"Castle Play", "Fairy Tale Series", "Castle Play", "Jerry Mouse",
"Rich Boy"}, {6, 4, 6, 14, 5}, 2

Output

26

Updated on: 02-Sep-2020

317 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements