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:
function solution(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].
function solution(A) {
// 초기값 [2..100,000]
if (A.length === 2) return Math.abs(A[0] - A[1])
let left = 0;
let right = A.reduce((prev,curr)=> prev+curr,0);
let min = Number.MAX_VALUE; //최소값을 최대로 잡아두었다. 이유는 밑에 스샷 첨부
for(let i=0;i<A.length -1;i++){
left += A[i];
right -= A[i];
const diff = Math.abs(left - right)
if( min > diff){
min = diff
}
}
return min
}
let min = 0 ;
let min = Math.abs(left -right);
했을 경우 80퍼만 성공을 하였다.
A의 값을 [-10, -20, -30, -40, 100] 주어진다면 min값이 초기값에서 변화가 없기 때문에
let min = Number.MAX_VALUE; // 최소값을 최대한을 두어서
if(min > diff )에 한번은 들어가 min값을 넣어야지 해결이 되기 떄문이다.
잘못이해했다면 댓글 부탁드립니다.
'IT > Algorithm' 카테고리의 다른 글
코딜리티(Codility) Lesson4 PermCheck 문제풀기 (0) | 2021.05.12 |
---|---|
코딜리티(Codility) Lesson4 MaxCounters (0) | 2021.03.24 |
코딜리티(Codility) Lesson3 PermMissingElem 문제풀기 (0) | 2021.03.02 |
코딜리티(Codility) Lesson3 FrogJmp 문제풀기 (0) | 2021.02.28 |
코딜리티(Codility) Lesson2 OddOccurrencesInArray 문제풀기 (javascript) (0) | 2021.02.28 |