Skip to content

Instantly share code, notes, and snippets.

@themichaelyang
Last active September 24, 2023 22:03
Show Gist options
  • Save themichaelyang/78797deef0e1124c8be715e59070bbcf to your computer and use it in GitHub Desktop.
Save themichaelyang/78797deef0e1124c8be715e59070bbcf to your computer and use it in GitHub Desktop.
class NumArray
def initialize(nums)
sum = 0
@prefix_sums = nums.map do |x|
sum += x
end
@prefix_sums.prepend(0)
end
def sum_range(left, right)
@prefix_sums[right + 1] - @prefix_sums[left]
end
end
@themichaelyang
Copy link
Author

class NumArray
  def initialize(nums)
    @nums = nums

    # instead of [0..i] as prefix, use [i..n] as postfix
    sum = 0
    @postfix_sum = nums.reverse.map do |value|
      sum += value
    end.reverse
  end

  def sum_range(left, right)
    @postfix_sum[left] - @postfix_sum[right] + @nums[right]
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment