상세 컨텐츠

본문 제목

Codility Lesson3 - TapeEquilibrium

카테고리 없음

by 허허지니 2023. 8. 21. 17:18

본문

A non-empty array A consisting of N integers is given. Array A represents numbers on a tape.

N개의 정수로 구성된 비어 있지 않은 배열 A가 제공됩니다. 배열 A는 테이프의 숫자를 나타냅니다.

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].

0 < P < N과 같은 임의의 정수 P는 이 테이프를 두 개의 비어 있지 않은 부분(A[0], A[1], ..., A[P], 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])|

두 부분의 차이는 |(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:

class Solution { public int solution(int[] A); }

that, given a non-empty array A of N integers, returns the minimal difference that can be achieved.

N개의 정수의 비어 있지 않은 배열 A가 주어지면 달성할 수 있는 최소 차이를 반환합니다.

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.

함수는 위에서 설명한 대로 1을 반환해야 합니다.

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은 [2..100,000] 범위 내의 정수입니다;
배열 A의 각 요소는 [-1,000..1,000] 범위 내의 정수입니다.


class Solution {
    public int solution(int[] A) {
        int answer = 0;
        int forth = A[0];
        int back = 0;
        int[] N = new int[A.length-1];

        for(int i = 1; i < A.length; i++) {
            back += A[i];
        }

        N[0] = Math.abs(forth - back);

        for(int i = 1; i < A.length-1; i++) {
            forth += A[i];
            back -= A[i];
            N[i] = Math.abs(forth - back);
        }
        answer = Arrays.stream(N).min().getAsInt();

        return answer;
    }
}