Playlist

You are given a playlist of a radio station since its establishment. The playlist has a total of n songs.

What is the longest sequence of successive songs where each song is unique?

Example:

Input:  n = 8, arr = {1, 2, 1, 3, 2, 7, 4, 2}
Output: 5

Approach

C++

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

int playList(int n, vector<int> &arr)
{

    set<int> st;
    int ans = 0;
    for (int i = 0, j = 0; j < n; j++)
    {
        if (st.count(arr[j]))
        {
            while (st.count(arr[j]))
                st.erase(arr[i++]);
        }
        st.insert(arr[j]);
        ans = max(ans, j - i + 1);
    }
    return ans;
}

int main()
{

    int n = 8;
    vector<int> arr = {1, 2, 1, 3, 2, 7, 4, 2};

    cout << playList(n, arr) << "\n";

    return 0;
}


No comments:

Post a Comment