Corporate Flight Bookings in Python

PythonServer Side ProgrammingProgramming

<p>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].</p><p>To solve this, we will follow these steps &minus;</p><ul class="list"><li>res := make one array of size n, and fill this with 0</li><li>for each entry i in bookings<ul class="list"><li>res[i[0] - 1] := res[i[0] - 1] + i[2]</li><li>if i[1] &lt; n, then res[i[1]] := res[i[1]] &ndash; i[2]</li></ul></li><li>for i in range 1 to n &ndash; 1<ul class="list"><li>res[i] := res[i] + res[i - 1]</li></ul></li><li>return res</li></ul><p>Let us see the following implementation to get better understanding &minus;</p><h2>Example</h2><p><a class="demo" href=" " rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate">class Solution(object): &nbsp; &nbsp;def corpFlightBookings(self, bookings, n): &nbsp; &nbsp; &nbsp; res = [0 for i in range(n)] &nbsp; &nbsp; &nbsp; for i in bookings: &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;res[i[0]-1]+=i[2] &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if(i[1]&lt;n): &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; res[i[1]]-=i[2] &nbsp; &nbsp; &nbsp; for i in range(1,n): &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;res[i]+=res[i-1] &nbsp; &nbsp; &nbsp; return res ob = Solution() print(ob.corpFlightBookings([[1,2,10],[2,3,20],[2,5,25]],5))</pre><h2>Input</h2><pre class="result notranslate">[[1,2,10],[2,3,20],[2,5,25]] 5</pre><h2>Output</h2><pre class="result notranslate">[10, 55, 45, 25, 25]</pre>
Updated on 30-Apr-2020 12:38:07