Open In App

Count people who can Watch the Movie

Last Updated : 07 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given N people are standing in a row and heights[], where the ith integer represents the height of the person. There is a movie screen at the rightmost position of the row. The ith person will be able to see the movie screen only if K persons, the immediate right side of the ith person, have a height less than the height of the person. The task is to count the number of people who will be able to watch the movie.

Examples:

Input: N = 5, K = 1, heights[] = {4, 3, 1, 2, 5}
Output: 3
Explanation: The 1st, 2nd and 5th person will be able to watch the movie, while the 3rd person can’t because of the 4th person whose height is greater than the 3rd person.

Approach: This can be solved with the following idea:

Using stack, we can find the person having a height greater than that of a person and check whether the distance between the next person is greater than k or not.

Below are the steps involved:

  • Initialize a stack s.
  • Start iterating from the right side i.e. i = N – 1.
  • If the current height is greater than heights present in the stack, pop them
    • If the stack becomes empty, enter the maximum value.
    • Otherwise, enter the index value having greater height.
  • To find count of people able to watch movie:
    • If v[i] – i > k, is true we will increment the count by 1, as v[i] represents the index of people having height greater.
    • If distance between v[i] – i is greater than k, person at index i will be able to watch movie.

Below is the implementation of the code:

C++




// C++ code for the above approach:
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
 
// Function to count number of people can watch
// the movie
int solve(int N, int K, vector<int> heights)
{
    vector<int> v;
    stack<int> s;
    int i = N - 2;
    v.push_back(9999999);
    s.push(N - 1);
    while (i >= 0) {
 
        // Current height is more than heights
        // present in stack
        while (!s.empty()
               && heights[s.top()] < heights[i]) {
            s.pop();
        }
 
        if (s.empty()) {
            v.push_back(9999999);
        }
        else {
            v.push_back(s.top());
        }
        s.push(i);
        i--;
    }
 
    reverse(v.begin(), v.end());
 
    i = 0;
    int count = 0;
    while (i < N) {
 
        // Check whether movie is visible or not
        if (v[i] - i > K) {
 
            count++;
        }
        i++;
    }
    return count;
}
 
// Driver code
int main()
{
 
    int N = 5;
    int K = 1;
    vector<int> heights = { 4, 3, 1, 2, 5 };
 
    // Function call
    cout << solve(N, K, heights);
    return 0;
}


Java




import java.util.Stack;
import java.util.Vector;
import java.util.Collections;
 
public class Main {
    // Function to count the number of people who can watch the movie
    public static int solve(int N, int K, Vector<Integer> heights) {
        Vector<Integer> v = new Vector<>();
        Stack<Integer> s = new Stack<>();
        int i = N - 2;
        v.add(9999999);
        s.push(N - 1);
 
        while (i >= 0) {
            while (!s.isEmpty() && heights.get(s.peek()) < heights.get(i)) {
                s.pop();
            }
 
            if (s.isEmpty()) {
                v.add(9999999);
            } else {
                v.add(s.peek());
            }
 
            s.push(i);
            i--;
        }
 
        Collections.reverse(v);
 
        i = 0;
        int count = 0;
 
        while (i < N) {
            if (v.get(i) - i > K) {
                count++;
            }
            i++;
        }
        return count;
    }
 
    // Driver code
    public static void main(String[] args) {
        int N = 5;
        int K = 1;
        Vector<Integer> heights = new Vector<>();
        heights.add(4);
        heights.add(3);
        heights.add(1);
        heights.add(2);
        heights.add(5);
 
        // Function call
        System.out.println(solve(N, K, heights));
    }
}


Python3




# Python code for the above approach:
 
# Function to count number of people who can
# watch the movie
def solve(N, K, heights):
    v = []
    s = []
    i = N - 2
    v.append(9999999)
    s.append(N - 1)
 
    # Iterate from the second last height to
    # the first one
    while i >= 0:
        # Current height is more than heights
        # present in stack
        while s and heights[s[-1]] < heights[i]:
            s.pop()
 
        if not s:
            v.append(9999999)
        else:
            v.append(s[-1])
        s.append(i)
        i -= 1
 
    v = v[::-1]
 
    i = 0
    count = 0
    while i < N:
        # Check whether the movie is
        # visible or not
        if v[i] - i > K:
            count += 1
        i += 1
    return count
 
# Driver code
 
N = 5
K = 1
heights = [4, 3, 1, 2, 5]
 
# Function call
print(solve(N, K, heights))


C#




using System;
using System.Collections.Generic;
 
class Geek
{
    // Function to count the number of the people who can watch the movie
    static int Solve(int N, int K, List<int> heights)
    {
        List<int> v = new List<int>();
        Stack<int> s = new Stack<int>();
        int i = N - 2;
        v.Add(9999999);
        s.Push(N - 1);
        // Process heights in the reverse order
        while (i >= 0)
        {
            // Current height is more than heights present in the stack
            while (s.Count > 0 && heights[s.Peek()] < heights[i])
            {
                s.Pop();
            }
            if (s.Count == 0)
            {
                v.Add(9999999);
            }
            else
            {
                v.Add(s.Peek());
            }
            s.Push(i);
            i--;
        }
        v.Reverse();
        i = 0;
        int count = 0;
        // Check whether the movie is visible or not
        while (i < N)
        {
            if (v[i] - i > K)
            {
                count++;
            }
            i++;
        }
        return count;
    }
    // Driver code
    static void Main()
    {
        int N = 5;
        int K = 1;
        List<int> heights = new List<int> { 4, 3, 1, 2, 5 };
        // Function call
        Console.WriteLine(Solve(N, K, heights));
    }
}


Javascript




function GFG(N, K, heights) {
    // Arrays to store the indices of the next greater element to
    // right for each element
    let v = [];
    // Stack to keep track of the indices
    let s = [];
    // Initialize the loop variable
    let i = N - 2;
    // Push a large value and the last index into
    // the arrays as placeholders
    v.push(9999999);
    s.push(N - 1);
    // Loop to fill the 'v' array with indices of
    // next greater element to the right
    while (i >= 0) {
        while (s.length > 0 && heights[s[s.length - 1]] < heights[i]) {
            s.pop();
        }
        if (s.length === 0) {
            v.push(9999999);
        } else {
            v.push(s[s.length - 1]);
        }
        // Push the current index onto the stack
        s.push(i);
        i--;
    }
    // Reverse the 'v' array to get the correct order of
    // next greater elements to the right
    v.reverse();
    // Reset the loop variable
    i = 0;
    // Initialize a counter for the number of the elements satisfying the condition
    let count = 0;
    // Loop through the array to check the condition
    while (i < N) {
        // If the difference between the next greater element to
        // right and the current index is greater than 'K'
        if (v[i] - i > K) {
            // Increment the counter
            count++;
        }
        i++;
    }
    // Return the final count
    return count;
}
// Driver code
function main() {
    // Input values
    const N = 5;
    const K = 1;
    const heights = [4, 3, 1, 2, 5];
    // Function call and print the result
    console.log(GFG(N, K, heights));
}
main();


Output

3








Time Complexity: O(N)
Auxiliary Space: O(N)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads