[codility]tape_equilibrium

http://codility.com/demo/take-sample-test/tapeequilibrium

简单题。记录到i为止的sum就可以了。O(n)。

// you can also use includes, for example:

// #include <algorithm>

int solution(vector<int> &A) {

    // write your code in C++98

    int total = 0;

    vector<int> sum;

    for (int i = 0; i < A.size(); i++) {

        total += A[i];

        sum.push_back(total);

    }

    int ans = 1 << 30;

    for (int i = 0; i < A.size() - 1; i++) {

        int tmp = (total - 2 * sum[i]);

        if (tmp < 0) tmp = -tmp;

        if (ans > tmp) ans = tmp;

    }

    return ans;

}

  

你可能感兴趣的:(lib)