# L3-TapeEquilibrium ###### tags: `Codility_lessons` ## Question https://app.codility.com/programmers/lessons/3-time_complexity/tape_equilibrium/ ## Key 直接用一個Loop迭代不同的p(位置),去算difference,然後取最小的就是答案,但如何避免用太多loop算difference才不會time exceed算是重點 先把總和算出來,因為loop是由小到大迭代,所以左邊的部分就直接累加,右邊的部分則在迭代過程中從總和扣除,這樣只需要一個loop ## Reference ## Solution ```cpp= #include <iostream> #include <algorithm> #include <vector> #include <numeric> using namespace std; int solution(vector<int> &A) { long diff = 0; int suml = A[0]; int sumr = accumulate(A.begin()+1, A.end(), 0); long tape = abs(suml - sumr); for(unsigned int i=1; i<A.size()-1; i++) { suml += A[i]; sumr -= A[i]; diff = abs(suml - sumr); if(diff<=tape) { tape = diff; } } return tape; } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up