- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Corporate Flight Bookings in Python
Suppose we have n flights, and they are labeled from 1 to n. We have a list of flight bookings. The i-th booking indicates using bookings[i] = [i, j, k] this means that we booked k seats from flights labeled i to j inclusive. Find an array answer of length n, showing the number of seats booked on each flight in order of their label. So if the input is like [[1,2,10],[2,3,20],[2,5,25]] and n = 5, then the output will be [10, 55, 45, 25, 25].
To solve this, we will follow these steps −
- res := make one array of size n, and fill this with 0
- for each entry i in bookings
- res[i[0] - 1] := res[i[0] - 1] + i[2]
- if i[1] < n, then res[i[1]] := res[i[1]] – i[2]
- for i in range 1 to n – 1
- res[i] := res[i] + res[i - 1]
- return res
Let us see the following implementation to get better understanding −
Example
class Solution(object): def corpFlightBookings(self, bookings, n): res = [0 for i in range(n)] for i in bookings: res[i[0]-1]+=i[2] if(i[1]<n): res[i[1]]-=i[2] for i in range(1,n): res[i]+=res[i-1] return res ob = Solution() print(ob.corpFlightBookings([[1,2,10],[2,3,20],[2,5,25]],5))
Input
[[1,2,10],[2,3,20],[2,5,25]] 5
Output
[10, 55, 45, 25, 25]
Advertisements
To Continue Learning Please Login
Login with Google