Post

[Programmers] #181884 - n보다 커질 때까지 더하기 [Java][C++][Python]

[Programmers] #181884 - n보다 커질 때까지 더하기 [Java][C++][Python]

문제 링크


1. 아이디어

배열을 앞에서부터 순회하며 누적합을 갱신하고, 누적합이 n을 처음으로 초과하는 순간 그 값을 반환하면 된다. n이 전체 원소의 합보다 작다고 보장되므로 순회가 끝나기 전에 반드시 조건을 만족하는 시점이 나온다.


2. 복잡도

접근시간공간
풀이$O(N)$$O(1)$

($N$ = numbers의 길이)


3. 코드

풀이 [Java][C++][Python]

1
2
3
4
5
6
7
8
9
10
11
class Solution {
    public int solution(int[] numbers, int n) {
        int sum = 0;
        for (int x : numbers) {
            sum += x;
            if (sum > n) return sum;
        }

        return -1;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
#include <bits/stdc++.h>
using namespace std;

int solution(vector<int> numbers, int n) {
    int sum = 0;
    for (int x : numbers) {
        sum += x;
        if (sum > n) return sum;
    }

    return -1;
}
1
2
3
4
5
from itertools import accumulate


def solution(numbers, n):
    return next(x for x in accumulate(numbers) if x > n)

This post is licensed under CC BY 4.0 by the author.