본문 바로가기

공부하자/Codility

[Codility] Lesson3. TapeEquilibrium (C#)

문제: app.codility.com/programmers/lessons/3-time_complexity/tape_equilibrium/

 

TapeEquilibrium coding task - Learn to Code - Codility

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

app.codility.com

 

            if (A.Length >= 2 && A.Length <= 100000)
            {
                int sum1 = 0;
                int sum2 = 0;

                for (int i = 0; i < A.Length; i++)
                {
                    if (i == 0)
                        sum1 = A[i];
                    else
                        sum2 = sum2 + A[i];
                }

                int result = Math.Abs(sum1 - sum2);
                for (int i = 2; i < A.Length; i++)
                {
                    sum1 = sum1 + A[i - 1];
                    sum2 = sum2 - A[i - 1];
                    if (result > Math.Abs(sum1 - sum2))
                        result = Math.Abs(sum1 - sum2);
                }
                return result;
            }

            return 0;