[백준] 11441번: 합 구하기

whitehousechef·2024년 12월 9일

initial

I tried solving the prefix sum question like how a human would solve it. It works but could be cleaner. But lets see code

import sys
input = sys.stdin.readline

n = int(input())
lst = list(map(int,input().split()))
ans = [0 for _ in range(n)]
ans[0] = lst[0]
for i in range(1,n):
    ans[i] += lst[i]+ans[i-1]

m= int(input())
for _ in range(m):
    a,b = map(int,input().split())
    if a>1:
        print(ans[b-1]-ans[a-2])
    else:
        print(ans[b-1])

solution

a better way is to add a 0 at the front of prefix sum list. This way, we dont have to separate our logic via if else statements like my impl.

import sys
input = sys.stdin.readline

N = int(input())
arr = [0] + list(map(int, input().split()))

prefix = [0] * len(arr)
for i in range(1, len(arr)):
    prefix[i] = prefix[i - 1] + arr[i]

M = int(input())
for _ in range(M):
    s, e = map(int, input().split())
    print(prefix[e] - prefix[s - 1])

complexity

n time and space

0개의 댓글