Need to reduce the time limit

Can anyone provide me with any hint as to how to reduce the time limit of this question. I passed 17 Test Cases and in 3 the time limit is exceeding.
In a superhero game, there is one supermarket with infinite superpowers. The price of a superpower is given for n days, where A[i] denotes the price of the superpower on the ith day. You are given q queries, each denoting a player who is willing to buy the superpower for price of atmost x.

For each player, find and print the last possible day that the player can purchase the superpower. If the purchase is not possible, print -1 .

For example, if the prices of the superpower for 5 days are given as 1,4,6,7,6 and you have a query where x=6. The last day where a player can purchase the power for that value is on day 5.

Input Format

The first line of the input contains n denoting the number of days.

Next line contains n space-separated positive integers, where the ith item denotes the cost of the superpower on the ith day.

Next line contains a single integer q denoting the total number of players.

Next, q lines contain a single integer x denoting the price which ith player wants to buy the superpower at.

Constraints

1 ≤ n ≤ 10^5
1 ≤ q ≤ 10^5
1 ≤ A[i] ≤ 10^9
1 ≤ x ≤ 10^9
Output Format

For each player, print -1 if the player can't buy the superpower on any of the days. Otherwise, print the maximum day on which the player can buy the superpower.

The following is my code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
  #include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
    int n;
    scanf("%d",&n);
    int arr[n];
    
    for(int i=0;i<n;i++)
    {
        scanf("%d",&arr[i]);
    }
    
    int q;
    scanf("%d",&q);
    int arr1[q];
    
    int x=0;
    
    for(int i=0;i<q;i++)
    {
        scanf("%d",&x);
        int c=0;
        for(int j=n-1;j>=0;j--)
        {
            if(x>=arr[j])
            {
                printf("%d\n",j+1);
                c=1;
                break;
            }
        }
        if(c==0)
        {
            printf("-1\n");
        }
    }
    
    return 0;
}
rewrite time.

store the N's in a hash lookup such that table[value] = max day for that value. You can do this iteratively ... in your example... 1,4,6,7,6 ... value 1 gets day 1, value 4 gets day 2, value 6 gets day 3, value 7 gets day 4, value 6 gets day 5 (over-write!) ... now query 6, get day 5.

eliminate for loopage in favor of direct answer.
profit.

Last edited on
Topic archived. No new replies allowed.