[Programmers] #181884 - n보다 커질 때까지 더하기 [Java][C++][Python]
[Programmers] #181884 - n보다 커질 때까지 더하기 [Java][C++][Python]
1. 아이디어
앞에서부터 원소를 더하다가 합이 $n$을 처음 넘는 순간의 합을 반환하는 문제다. 지문에 $n$이 모든 원소의 합보다 작다는 조건이 있어 끝까지 더하면 반드시 $n$을 넘으므로, 합이 $n$을 넘지 못한 채 끝나는 경우는 생기지 않는다.
2. 코드
풀이 [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)
accumulate가 누적 합을 하나씩 내놓는 이터레이터라서 next로 처음 n을 넘는 값에서 바로 멈췄다. 합이 반드시 n을 넘는 조건이라 next에 기본값은 두지 않았다.
This post is licensed under CC BY 4.0 by the author.