Original link: https://leetcode.com/problems/corporate-flight-bookings/
Example:
Input: bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5
Output: [10,55,45,25,25]
Intuitive method:
Initialize an array whose length is equal to n.
For each record, do increments to each elements.
Code:
class Solution(object):
def corpFlightBookings(self, bookings, n):
"""
:type bookings: List[List[int]]
:type n: int
:rtype: List[int]
"""
op = [0 for i in range(n)]
d = dict()
for i in bookings:
tag = str(i[0]) + "-" + str(i[1])
if tag in d:
d[tag] += i[2]
else:
d[tag] = i[2]
for i in d:
intervals = i.split("-")
for t in range(int(intervals[0])-1, int(intervals[1])):
op[t] += d[i]
return op
This code runs in O(ML) where M is the number of records and L is the average length of each record.
This code failed when submitted because of Time Limit Exceeded.
Inspired by the above link, the cumulative sum seems to help.
When the code contains lots of “same” array operations, cumulative sum might help.
Code:
class Solution(object):
def corpFlightBookings(self, bookings, n):
"""
:type bookings: List[List[int]]
:type n: int
:rtype: List[int]
"""
op = [0 for i in range(n+1)]
for lo, hi, num in bookings:
op[lo-1] += num
op[hi] -= num
for i in range(n-1):
op[i+1] += op[i]
return op[:-1]
The new version runs in O(booking + N) time and O(N) space.