Problem
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].
Copyright 2009–2020 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited
How to solve
- 정보
N개의 정수를 가진 배열 A: 테이프의 수
정수 P, 0<P<N 은 테이프를 2개의 파트로 자른다
2개의 파트의 차는 (A[0] + A[1] + ... + A[P − 1]) − (A[P] + A[P + 1] + ... + A[N − 1])
- 구해야 하는것?
배열 A를 반으로 잘랐을 때, 두 부분의 차가 가장 작은 값 return
- 풀이
각 idx에서의 배열의 sum 을 구해놓고 계산
left sum =sum[i-1]
right sum = sum[len-1] - sum[i-1]
**주의**
배열의 갯수가 2인 경우 조건 !
Solution(c++)
// you can use includes, for example:
#include <bits/stdc++.h>
// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;
int solution(vector<int> &A) {
// write your code in C++14 (g++ 6.2.0)
int len = A.size();
int minVal = INT_MAX;
vector<int> sum(len, 0);
if(len == 2){
return A[1] - A[0];
}
sum[0] = A[0];
for(int i=1; i<len; i++){
sum[i] = sum[i-1] + A[i];
}
for(int i=1; i<len; i++){
minVal = min(abs(sum[i-1] - (sum[len-1]- sum[i-1])), minVal);
}
return minVal;
}
Test Result
app.codility.com/demo/results/training5GHYY4-W3M/
'SW > 알고리즘 문제풀이' 카테고리의 다른 글
[Codility] Lesson4 - Counting Elements : Perm Check (c++) (0) | 2020.12.20 |
---|---|
[Codility] Lesson4 - Counting Elements: Frog River One (c++) (0) | 2020.12.19 |
[Codility] Lesson3 - Time Complexity : Perm Missing Elem (c++) (0) | 2020.12.18 |
[Codility] Lesson2 - Arrays: Odd Occurrences In Array (c++) (1) | 2020.12.18 |
[leet code] Linked List Random Node (python) (0) | 2020.12.17 |
댓글