1109. Corporate Flight Bookings
Problem
Flights are numbered 1…n. bookings[i] = [first, last, seats] reserves seats seats on every flight from first to last. Return the total number of seats reserved on each flight.
Example: bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5 → [10,55,45,25,25]
Constraints: n and the number of bookings ≤ 2·10⁴.
Each booking adds seats to a range of flights: d[first] += seats, d[last + 1] -= seats. One prefix-sum pass produces all totals.
Complexity: O(n + bookings).
class Solution:
def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:
d = [0] * (n + 1)
for first, last, seats in bookings:
d[first - 1] += seats
d[last] -= seats
return list(itertools.accumulate(d[:n]))
assert Solution().corpFlightBookings([[1, 2, 10], [2, 3, 20], [2, 5, 25]], 5) == [10, 55, 45, 25, 25]
assert Solution().corpFlightBookings([[1, 2, 10], [2, 2, 15]], 2) == [10, 25]
class Solution {
public int[] corpFlightBookings(int[][] bookings, int n) {
int[] d = new int[n + 1];
for (int[] b : bookings) { d[b[0] - 1] += b[2]; d[b[1]] -= b[2]; }
int[] res = new int[n];
for (int i = 0, s = 0; i < n; i++) res[i] = s += d[i];
return res;
}
}
func corpFlightBookings(bookings [][]int, n int) []int {
d := make([]int, n+1) // difference array: +seats at first, -seats after last
for _, b := range bookings {
d[b[0]-1] += b[2]
d[b[1]] -= b[2]
}
res := make([]int, n)
run := 0
for i := 0; i < n; i++ {
run += d[i]
res[i] = run
}
return res
}