Finding leaders in an array

 Finding leaders in an array

Here I have written the Two approach one is naive approach which will take O(n^2) time complexity and another is the efficient approach which will take O(n) time complexity.

Naive solution

#include <iostream>

// naive approach;

int leader(int arr[], int n)
{
    for (int i = 0; i < n; i++)
    {
        bool flag = false;
        for (int j = i + 1; j < n; j++)
        {
            if (arr[i] <= arr[j])
            {
                flag = true;
                break;
            }
        }
        if (flag == false)
        {
            std::cout << arr[i] << ' ';
        }
    }
}

int main()
{
    int arr[] = {2, 5, 10, 7, 4};
    int n = 5;
    std::cout << "The size of the array = " << n << std::endl;
    leader(arr, n);
    return 0;
}

Efficient solution

#include <iostream>
//efficient solution
void leader(int arr[], int n)
{
    int curr_lad = arr[n - 1];
    std::cout << curr_lad << ' ';
    for (int i = n - 2; i >= 0; i--)
    {
        if (curr_lad < arr[i])
        {
            curr_lad = arr[i];
            std::cout << curr_lad << ' ';
        }
    }
}

int main()
{
    int arr[] = {1, 3, 4, 10, 2};
    int size = sizeof(arr) / sizeof(arr[0]);
    std::cout << "The size of the array = " << size << std::endl;
    leader(arr, size);
    return 0;
}

Post a Comment

0 Comments