Develop / Leetcode April 9, 2024

Daily Question – 2073. Time Needed to Buy Tickets

Description: https://leetcode.com/problems/time-needed-to-buy-tickets/description/

Code: Time complexity O(n2)

public static int timeRequiredToBuy(int[] tickets, int k) {
        int count = 0;
        while (tickets[k] > 0) {
            for (int i=0;i<tickets.length;i++) if (tickets[i] > 0) {
                tickets[i]--;
                count++;
                if (tickets[k] == 0) return count;
            }
        }
        return count;
    }

Can be simplified to O(n) as we do not need to iterate every time to count the time.

public static int timeRequiredToBuy(int[] tickets, int k) {
    int time = 0;
    for (int i = 0; i < tickets.length; i++) {
        if (i <= k) {
            // 对于索引k及之前的人,我们取他们的票数与k的票数的较小值
            time += Math.min(tickets[i], tickets[k]);
        } else {
            // 对于索引k之后的人,我们只需要考虑在k之前他们能买的票数
            time += Math.min(tickets[i], tickets[k] - 1);
        }
    }
    return time;
}

You may also like...

Apr
07
2023
0

2023 Qiandao Lake Cycling Around 环千岛湖骑行

临时心血来潮,想去环千岛湖骑行,说干就干,想到想做的事情就马上去做,买票出发,于是有了这段行程…

Feb
14
2024
0

Daily Question – 2149. Rearrange Array Elements by Sign

The positive number would always on the odd position while negative number would on the double position.

Apr
03
2024
0

Daily Question – 79. Word Search

Post Views: 40 Description: https://leetcode.com/problems/word-search/description/?envType=daily-question&envId=2024-04-03 Notes: BFS and backtracking. Using a boolean 2-D array to reserve...