If you have asked for an array where you need to add sum from one position to another position and you must do the work in O(N) time.
Then what should you do?
Then you need to start the position where you started counting & set the given value on that position. The next work is to add the (final+1) position and subtract the value.
Example:
Add 10 on (1 to 2) position
Add 20 on (2 to 3) position
Add 25 on (2 to 5) position
Addition point set (10 on 1st position:20 on 2nd position:25 on 2nd position)
Subtraction point set (10 on 3rd position:20 on 4th position:25 on 6th position)
Array | Array [1] | Array [2] | Array [3] | Array [4] | Array [5] | Extra |
After adding 10 | 10 |
| -10 |
|
|
|
After adding 20 |
| 20 |
| -20 |
|
|
After adding 25 |
| 25 |
|
|
| -25 |
Kept value | 10 | 45 | -10 | -20 |
| -25 |
After that just add the number with previous value. So, the answer array.
Array | Array [1] | Array [2] | Array [3] | Array [4] | Array [5] | Extra |
Kept Value | 10 | 45 | -10 | -20 | 0 | -25 |
Answer | 10 | 55 | 45 | 25 | 25 | 0 |
So, we just imagine that 10 is added on position 1 & position 2 on the array. After that when we subtract –10 that means the value vanished on position 3.
Problem: https://leetcode.com/problems/corporate-flight-bookings/
Code in C++:
solution:
class Solution { public: vector<int> corpFlightBookings(vector<vector<int>>& bookings, int n) { vector<int>ans(n),pr(n+2); for(int i=0;i<bookings.size();i++) { int start=bookings[i][0]; int stop=bookings[i][1]; int val=bookings[i][2]; pr[start]+=val; pr[stop+1]+=((-1)*val); } for(int i=1;i<=n;i++) { if(i==1) ans[i-1]=pr[i]; else ans[i-1]=ans[i-2]+pr[i]; } return ans; } };
Comments
Post a Comment