Norway


#include <iostream>

#include <unordered_map>

using namespace std;

 

// Utility function to the sub- formed by A[i, j]

void printSubArray(int A[], int i, int j, int n)

{

    if (i < 0 || i > j || j >= n) // invalid input

        return;

 

    for (int index = i; index < j; index++)

        cout << A[index] << “, “ ;

 

    cout << A[j] << endl;

}

 

// Function to print all sub-arrays having

void calculate(int A[], int n)

{

    // Map to mark elements as visited in the current window

    unordered_map<int, bool> visited;

 

    // points to left and right boundary of the current window

    // i.e. current window is formed by A[left, right]

    int right = 0, left = 0;

 

    // loop until right index of the current window is less

    // than the maximum index

    while (right < n)

    {

        // keep increasing the window size if all elements in the

        // current window are distinct

        while (right < n && !visited[A[right]])

        {

            visited[A[right]] = true;

            right++;

        }

 

        printSubArray(A, left, right 1, n);

 

        // As soon as duplicate is found (A[right]), terminate the above loop

        // and reduce the window’s size from its left to remove the duplicate

        while (right < n && visited[A[right]])

        {

            visited[A[left]] = false;

            left++;

        }

    }

}

 

// main function

int main()

{

    int A[] = { 5, 2, 3, 5, 4, 3 };

    int n = sizeof A / sizeof A[0];

 

    calculate(A, n);

 

    return 0;

}



Source link

LEAVE A REPLY

Please enter your comment!
Please enter your name here