Codility Lekcja 3.3: TapeEquilibrium. Podejście 2/2

preview_player
Показать описание

---

Рекомендации по теме
Комментарии
Автор

public int solution(int[] A) {
int rightSum = 0;
for (int a : A) {
rightSum += a;
}
int leftSum = A[0];
rightSum -= leftSum;
int minimumDifference = Math.abs(rightSum - leftSum);
for (int i = 1; i < A.length - 1; i++) {
leftSum += A[i];
rightSum -= A[i];
int actualDifference = Math.abs(rightSum - leftSum);
minimumDifference = Math.min(actualDifference, minimumDifference);
}
return minimumDifference;
}

lukke
Автор

Można pozbyć się tych tablic ;)
Kod w c#


public int solution(int[] A)
{
int leftSum = A[0];
int rightSum = A.Sum() - leftSum;
int bestDifference = Math.Abs(leftSum - rightSum);

for (int i = 1; i < A.Length - 1; i++)
{
leftSum += A[i];
rightSum -= A[i];
int difference = Math.Abs(leftSum - rightSum);

if (difference < bestDifference)
{
bestDifference = difference;
}
}

return bestDifference;
}

rikoradzio
Автор

Super! Czekam na kolejne odcinki niczym na Boże Narodzenie :D

HasNoName