문제
A non-empty array A consisting of N integers is given. Array A represents numbers on a tape.
Any integer P, such that 0 < P < N, splits this tape into two non-empty parts: A[0], A[1], ..., A[P − 1] and A[P], A[P + 1], ..., A[N − 1].
The difference between the two parts is the value of: |(A[0] + A[1] + ... + A[P − 1]) − (A[P] + A[P + 1] + ... + A[N − 1])|
In other words, it is the absolute difference between the sum of the first part and the sum of the second part.
For example, consider array A such that:
A[0] = 3 A[1] = 1 A[2] = 2 A[3] = 4 A[4] = 3
We can split this tape in four places:
- P = 1, difference = |3 − 10| = 7
- P = 2, difference = |4 − 9| = 5
- P = 3, difference = |6 − 7| = 1
- P = 4, difference = |10 − 3| = 7
Write a function:
int solution(vector<int> &A);
that, given a non-empty array A of N integers, returns the minimal difference that can be achieved.
For example, given:
A[0] = 3 A[1] = 1 A[2] = 2 A[3] = 4 A[4] = 3
the function should return 1, as explained above.
Write an efficient algorithm for the following assumptions:
- N is an integer within the range [2..100,000];
- each element of array A is an integer within the range [−1,000..1,000].
N 크기의 벡터를 1~N-1의 인덱스를 기준으로 나눴을 때의, 합의 차이의 최솟값을 구하시오.
합의 차이는 pivot이 2인 경우에는 0~1까지의 합과 1~N-1까지의 합을 각각 구한 뒤, 그 차이를 구하면 된다.
풀이
단순하게 1~N-1 사이를 피벗으로 삼아 나눈 양쪽의 합을 구하니 시간 초과가 나와서 어떻게 해야할지 한참 고민했다.
그래서 앞에서부터의 합, 뒤에서부터의 합을 구해놓은 배열을 선언하여, 그 두 차이의 최솟값을 정답으로 삼았다.
(두 배열의 i번째에는 각각 0~i-1까지의 합과 i~N-1까지의 합을 저장하고 있다.)
코드
int solution(vector<int> &A) {
int size = A.size();
int *front = new int[size];
int *end = new int[size];
front[1] = A[0]; // 0 ~ i-1까지의 합
for (int i = 2; i < size; i++) {
front[i] = front[i - 1] + A[i - 1];
}
end[size - 1] = A[size - 1]; // i ~ N-1까지의 합
for (int i = size - 2; i > 0; i--) {
end[i] = end[i + 1] + A[i];
}
int min = 999999;
for (int i = 1; i < size; i++) {
int diff = abs(front[i] - end[i]); // 차이가 가장 작은 경우를 찾음
if (diff < min)
min = diff;
}
return min;
}
'Old > Codility' 카테고리의 다른 글
Codility - Missing Integer // C++ (0) | 2020.02.06 |
---|---|
Codility - Perm Check // C++ (0) | 2020.02.06 |
Codility - Frog River One // C++ (0) | 2020.02.02 |
Codility - Frog Jmp // C++ (0) | 2020.02.02 |
Codility - Perm Missing Elem // C++ (0) | 2020.02.01 |