Lesson3 - TapeEquilibrium

作成日:2018/3/14
TapeEquilibrium coding task - Learn to Code - Codility

// you can also use imports, for example:
// import java.util.*;

// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");

class Solution {
    public static int solution(int[] A) {
        // write your code in Java SE 8

        int p = A.length - 1;     //4
        int left = 0;
        int right = 0;
        int smallest = -1;
        int ans = 0;

        right = A[p];   // A[p]
        for(int j = p - 1; j >= 0; j--) {   // A[0 ~ p-1]
          left += A[j];
        }

        if ((ans = left - right) < 0) {
            ans *= -1;
        }
        smallest = ans;

        for(int i = p - 1; i > 0; i--) {    // 3~0
            left -= A[i];
            right += A[i];

            if ((ans = left - right) < 0) {
                ans *= -1;
            }

            if (ans < smallest ) {
              smallest = ans;
            }
        }

        return smallest;

    }
}