You are given an array of flight bookings bookings, where bookings[i] = [firsti, lasti, seatsi] represents a booking for flights firsti through
lasti (inclusive) with seatsi seats reserved for each flight in the range.
Return an arrayanswerof lengthn, whereanswer[i]is the total number of seats reserved for flighti.
Instead of updating every flight in each booking, we can use a difference array to efficiently apply range updates. By marking the start and end+1 of each booking, we can later compute the total seats for each flight using a prefix sum.
classSolution {
publicint[]corpFlightBookings(int[][] bookings, int n) {
int[] ans =newint[n];
for (int[] b : bookings) {
ans[b[0]-1]+= b[2];
if (b[1]< n) ans[b[1]]-= b[2];
}
for (int i = 1; i < n; ++i) ans[i]+= ans[i-1];
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
funcorpFlightBookings(bookings: Array<IntArray>, n: Int): IntArray {
val ans = IntArray(n)
for (b in bookings) {
ans[b[0]-1] += b[2]
if (b[1] < n) ans[b[1]] -= b[2]
}
for (i in1 until n) ans[i] += ans[i-1]
return ans
}
}
1
2
3
4
5
6
7
8
9
10
classSolution:
defcorpFlightBookings(self, bookings: list[list[int]], n: int) -> list[int]:
ans = [0] * n
for first, last, seats in bookings:
ans[first-1] += seats
if last < n:
ans[last] -= seats
for i in range(1, n):
ans[i] += ans[i-1]
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
impl Solution {
pubfncorp_flight_bookings(bookings: Vec<Vec<i32>>, n: i32) -> Vec<i32> {
let n = n asusize;
letmut ans =vec![0; n];
for b in bookings {
ans[(b[0]-1) asusize] += b[2];
if b[1] < n asi32 {
ans[b[1] asusize] -= b[2];
}
}
for i in1..n {
ans[i] += ans[i-1];
}
ans
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
corpFlightBookings(bookings: number[][], n: number):number[] {
constans=new Array(n).fill(0);
for (const [first, last, seats] ofbookings) {
ans[first-1] +=seats;
if (last<n) ans[last] -=seats;
}
for (leti=1; i<n; ++i) ans[i] +=ans[i-1];
returnans;
}
}