> For the complete documentation index, see [llms.txt](https://netjimmy.gitbook.io/code-interview-note/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://netjimmy.gitbook.io/code-interview-note/companies_summary/hackerrank.md).

# Hackerrank

## Buying show ticket

Given an array, tickets, of n positive integers describing initial sequence of people standing in line. Each ticketsi describes number of tickets that a person waiting at initial place. An integer p, denoting Jesse's position in tickets. Return the waiting time

[Source](https://stackoverflow.com/questions/43950000/hackerrank-buying-show-tickets-optimization)

* Divide array by index p.
* In first half, count the number only it is greater than ticket\[i], otherwise return p
* In second half the same, but return number - 1

```java
private int buy(int[] tickets, int p){
    int count=tickets[p];
    for(int i=0; i<p; i++){
        if(tickets[i]>p) count+=tickets[p];
        else count+=tickets[i];
    }
    for(int i=p+1; i<tickets.length;i++){
        if(tickets[i]>p) count+=tickets[p]-1;
        else count+=tickets[i]-1;
    }
    return count;
}

public static void main(String[] args) {
    buyTickets b1 = new buyTickets();
    int[] tickets1 = new int[]{2,6,3,4,5};
    System.out.println(b1.buy(tickets1, 2)); // return 12
    int[] tickets2 = new int[]{5,5,2,3,3};
    System.out.println(b1.buy(tickets2, 2)); // return 8
}
```
