RainX_69

RANGE ADDITION (MUST DO) LINE SWEEP PROBLEM

Feb 7th, 2023
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.39 KB | Source Code | 0 0
  1. ASKED IN GOOGLE - https://www.lintcode.com/problem/903/
  2.  
  3. Assume you have an array of length n initialized with all 0's and are given k update operations.
  4.  
  5. Each operation is represented as a triplet: [startIndex, endIndex, inc] which increments each element of subarray A[startIndex ... endIndex] (startIndex and endIndex inclusive) with inc.
  6.  
  7. Return the modified array after all k operations were executed.
  8.  
  9. Example
  10.  
  11. Given: length = 5,
  12. updates =
  13. [
  14. [1,  3,  2],
  15. [2,  4,  3],
  16. [0,  2, -2]
  17. ]
  18. return [-2, 0, 3, 5, 3]
  19.  
  20. Explanation:
  21. Initial state:
  22. [ 0, 0, 0, 0, 0 ]
  23. After applying operation [1, 3, 2]:
  24. [ 0, 2, 2, 2, 0 ]
  25. After applying operation [2, 4, 3]:
  26. [ 0, 2, 5, 5, 3 ]
  27. After applying operation [0, 2, -2]:
  28. [-2, 0, 3, 5, 3 ]
  29.  
  30. ---------------------------------------------------------------------------------------------------------------------------------------
  31.  
  32. ITS CALLED THE "LINE SWEEP ALGORITHM"
  33.  
  34. class Solution {
  35. public:
  36.    vector<int> getModifiedArray(int n, vector<vector<int>> &updates) {
  37.        vector<int> res(n,0);
  38.        for(auto update: updates){
  39.            int start=update[0];
  40.            int end=update[1];
  41.            int inc=update[2];
  42.            res[start]+=inc;;
  43.            if(end+1<n){
  44.                res[end+1]-=inc;
  45.            }
  46.        }
  47.        for(int i=1;i<n;i++){
  48.            res[i]+=res[i-1];
  49.        }
  50.        return res;
  51.    }
  52. };
Advertisement
Add Comment
Please, Sign In to add comment