Advertisement
exmkg

Untitled

Aug 5th, 2024
226
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.59 KB | None | 0 0
  1. class NumArray {
  2.     int[] prefix;
  3.  
  4.     // arr was 1-indexed, but nums is 0-indexed.
  5.     public NumArray(int[] nums) {
  6.         int n = nums.length;
  7.  
  8.         // `prefix` array is 1-indexed because it greatly simplifies computations.
  9.         // If `prefix` array would be 0-indexed, we'd have to always consider the case
  10.         // when i = 0 or left = 0 separately, so that we don't go out-of-bounds.
  11.         prefix = new int[n + 1]; // prefix[0 .. n]
  12.        
  13.         //            0  1  2   3  4   5
  14.         // nums =   [-2, 0, 3, -5, 2, -1]
  15.  
  16.         //            0   1   2   3   4   5   6
  17.         // prefix = [ 0, -2, -2,  1, -4, -2, -3]
  18.  
  19.         // prefix[0] = 0 because it is semantically equal to an empty prefix (which has zero sum).
  20.         prefix[0] = 0;
  21.         for (int i = 1; i <= n; i++) {
  22.             // prefix[i] =
  23.             //             sum(nums[1 .. i - 1]) +
  24.             //             nums[i]
  25.             prefix[i] = prefix[i - 1] + nums[i - 1];
  26.  
  27.             // nums[i - 1] (not nums[i]) because `nums` array is 0-indexed.
  28.         }
  29.     }
  30.  
  31.     public int sumRange(int left, int right) {
  32.         // Increment by 1 because `prefix` array is 1-indexed.
  33.         left++; right++;
  34.  
  35.         // nums[left] + ... nums[right]
  36.         // =
  37.         // sum(nums[1 .. right]) -
  38.         // sum(nums[1 .. left - 1]) =
  39.         // sum(nums[left .. right])
  40.         return prefix[right] - prefix[left - 1];
  41.     }
  42. }
  43.  
  44. /**
  45.  * Your NumArray object will be instantiated and called as such:
  46.  * NumArray obj = new NumArray(nums);
  47.  * int param_1 = obj.sumRange(left,right);
  48.  */
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement