1109. Corporate Flight Bookings
There are n flights that are labeled from 1 to n.
You are given an array of flight bookings bookings, where b o o k i n g s i = f i r s t i , l a s t i , s e a t s i bookingsi = first_i, last_i, seats_i bookingsi=firsti,lasti,seatsi represents a booking for flights f i r s t i first_i firsti through l a s t i last_i lasti (inclusive) with s e a t s i seats_i seatsi seats reserved for each flight in the range.
Return an array answer of length n , where answeri is the total number of seats reserved for flight i.
Example 1:
Input: bookings = \[1,2,10,2,3,20,2,5,25], n = 5
Output: 10,55,45,25,25
Explanation:
Flight labels: 1 2 3 4 5
Booking 1 reserved: 10 10
Booking 2 reserved: 20 20
Booking 3 reserved: 25 25 25 25
Total seats: 10 55 45 25 25
Hence, answer = 10,55,45,25,25
Example 2:
Input: bookings = \[1,2,10,2,2,15], n = 2
Output: 10,25
Explanation:
Flight labels: 1 2
Booking 1 reserved: 10 10
Booking 2 reserved: 15
Total seats: 10 25
Hence, answer = 10,25
Constraints:
- 1 < = n < = 2 ∗ 10 4 1 <= n <= 2 * 10^4 1<=n<=2∗104
- 1 < = b o o k i n g s . l e n g t h < = 2 ∗ 10 4 1 <= bookings.length <= 2 * 10^4 1<=bookings.length<=2∗104
- bookingsi.length == 3
- 1 < = f i r s t i < = l a s t i < = n 1 <= first_i <= last_i <= n 1<=firsti<=lasti<=n
- 1 < = s e a t s i < = 10 4 1 <= seatsi <= 10^4 1<=seatsi<=104
From: LeetCode
Link: 1109. Corporate Flight Bookings
Solution:
Ideas:
use a difference array, add seats at first, subtract after last, then take prefix sum.
Code:
c
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* corpFlightBookings(int** bookings, int bookingsSize, int* bookingsColSize, int n, int* returnSize) {
int* ans = (int*)calloc(n, sizeof(int));
*returnSize = n;
for (int i = 0; i < bookingsSize; i++) {
int first = bookings[i][0] - 1;
int last = bookings[i][1] - 1;
int seats = bookings[i][2];
ans[first] += seats;
if (last + 1 < n) {
ans[last + 1] -= seats;
}
}
for (int i = 1; i < n; i++) {
ans[i] += ans[i - 1];
}
return ans;
}