Skip to content

Instantly share code, notes, and snippets.

@EXJUSTICE
Created February 11, 2020 11:09
Show Gist options
  • Save EXJUSTICE/f121bea7bc17f1e11a51b0207b38bb8b to your computer and use it in GitHub Desktop.
Save EXJUSTICE/f121bea7bc17f1e11a51b0207b38bb8b to your computer and use it in GitHub Desktop.
def sumInRange(nums, queries):
#Create a list of 0s of equal to nums length
#Also create a sum counter
sum_at = [0] * len(nums)
total = 0
#First step - IGNORE THE QUERIES, Create maximum ASCENDING SUM by adding SUM THUS FAR TO EACH INDEX
#Add the value in nums to the counter, while adding the
for i, x in enumerate(nums):
total += nums[i]
sum_at[i] = total
#Then simply go through the the queries to identifiy indexes, take the subsections of consecutive sum at each index and subtract!
ans = [0] * len(nums)
for i, q in enumerate(queries):
start, end = q[0], q[1]
if start == 0:
ans[i] = sum_at[end]
else:
ans[i] = sum_at[end] - sum_at[start - 1]
return sum(ans) % (10**9 + 7) #read the whole problem!
######### SImiliar Approach
def sumInRange(nums, queries):
#At position 0 we naturally have 0 sum, we need to move to find sums
prefix_sum=[0]
sum_so_far = 0
for num in nums:
sum_so_far += num
prefix_sum.append(sum_so_far)
#Append sum thus far
total_sum = 0
for qurie_set in queries:
start = qurie_set[0]
end = qurie_set[1] + 1
total_sum += prefix_sum[end] - prefix_sum[start]
return total_sum % 1000000007
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment