devdk2208

Range Addition 1

Sep 4th, 2025 (edited)
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.16 KB | Software | 0 0
  1. Description
  2. Assume you have an array of length n initialized with all 0's and are given k update operations.
  3.  
  4. 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.
  5.  
  6. Return the modified array after all k operations were executed.
  7.    
  8.    
  9. Given:
  10. length = 5,
  11. updates =
  12. [
  13. [1,  3,  2],
  14. [2,  4,  3],
  15. [0,  2, -2]
  16. ]
  17. return [-2, 0, 3, 5, 3]
  18.  
  19. Explanation:
  20. Initial state:
  21. [ 0, 0, 0, 0, 0 ]
  22. After applying operation [1, 3, 2]:
  23. [ 0, 2, 2, 2, 0 ]
  24. After applying operation [2, 4, 3]:
  25. [ 0, 2, 5, 5, 3 ]
  26. After applying operation [0, 2, -2]:
  27. [-2, 0, 3, 5, 3 ]
  28.  
  29. Solution :
  30.  
  31.  
  32.  
  33. class Solution {
  34. public:
  35.    vector<int> getModifiedArray(int length, vector<vector<int>> &updates) {
  36.         vector<int> ans(length, 0);
  37.        
  38.        for(int i=0; i<updates.size(); i++){
  39.             int s = updates[i][0], e = updates[i][1], val = updates[i][2];
  40.            ans[s] += val;
  41.            if(e+1<length)  ans[e+1] += -val;
  42.        }
  43.  
  44.        for(int i=1; i<length; i++){
  45.            ans[i] += ans[i-1];
  46.        }
  47.        return ans;
  48.    }
  49. };
Advertisement
Add Comment
Please, Sign In to add comment