0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[100%] TapeEquilibrium (codility lessons)

Last updated at Posted at 2020-12-19

Painless

TapeEquilibrium

Minimize the value |(A[0] + ... + A[P-1]) - (A[P] + ... + A[N-1])|.
image.png

タスク説明

N個の整数で構成される空でない配列Aが与えられます。配列Aは、テープ上の数字を表します。

0 <P <Nのような任意の整数Pは、このテープを2つの空でない部分に分割します:A [0]、A [1]、...、A [P −1]およびA [P]、A [ P + 1]、...、A [N −1]。

2つの部分の違いは、次の値です。|(A [0] + A [1] + ... + A [P − 1])−(A [P] + A [P + 1] +.。 。+ A [N − 1])|

言い換えれば、それは最初の部分の合計と2番目の部分の合計の間の絶対差です。

たとえば、次のような配列Aについて考えてみます。

  A [0] = 3
  A [1] = 1
  A [2] = 2
  A [3] = 4
  A [4] = 3

このテープは4つの場所に分割できます。

P = 1、差= | 3 − 10 | = 7
P = 2、差= | 4 − 9 | = 5
P = 3、差= | 6 − 7 | = 1
P = 4、差= | 10 − 3 | = 7

関数を書く:

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

これは、N個の整数の空でない配列Aが与えられた場合、達成できる最小の差を返します。

たとえば、次のようになります。

  A [0] = 3
  A [1] = 1
  A [2] = 2
  A [3] = 4
  A [4] = 3

上で説明したように、関数は1を返す必要があります。

次の仮定のための効率的なアルゴリズムを記述します。

  • Nは[2..100,000]の範囲内の整数です。
  • 配列Aの各要素は、[-1,000..1,000]の範囲内の整数です。

解く

image.png

Program

TapeEquilibriumSolution.java

TapeEquilibriumSolution.java
    public int solution(int[] A) {
        int difference = 0;
        int sumPart1 = 0;
        int sumPart2 = 0;
        int sum = 0;

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

        sumPart1 = A[0];
        sumPart2 = sum - sumPart1;
        difference = Math.abs(sumPart1 - sumPart2);
        for (int p = 2; p < A.length; p++) {
            sumPart1 += A[p - 1];
            sumPart2 -= A[p - 1];
            int temp = Math.abs(sumPart1 - sumPart2);
            if (temp < difference) {
                difference = temp;
            }
        }

        return difference;
    }

Detected time complexity:
O(N)

jUnit

PermCheckSolutionTest.java

Report

Candidate Report: trainingAVSN2R-5SF


See also: CodilityのLessonsをすべて解く(更新中)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?