-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
aabdefc
commit 3cdaabe
Showing
3 changed files
with
49 additions
and
1 deletion.
There are no files selected for viewing
25 changes: 25 additions & 0 deletions
25
src/main/java/codility/p03_time_complexity/TapeEquilibrium.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
package codility.p03_time_complexity; | ||
|
||
/* | ||
https://app.codility.com/programmers/lessons/3-time_complexity/tape_equilibrium/ | ||
*/ | ||
public class TapeEquilibrium { | ||
|
||
/* | ||
https://app.codility.com/demo/results/training2QRQ7D-TBR/ | ||
*/ | ||
public int solution(int[] A) { | ||
long sum = 0; | ||
for (int value : A) sum += value; | ||
|
||
long firstSum = A[0]; | ||
long secondSum = sum - A[0]; | ||
long minDifference = Math.abs(secondSum - firstSum); | ||
for (int p = 1; p < A.length - 1; p++) { | ||
firstSum += A[p]; | ||
secondSum -= A[p]; | ||
minDifference = Math.min(minDifference, Math.abs(secondSum - firstSum)); | ||
} | ||
return (int) minDifference; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
23 changes: 23 additions & 0 deletions
23
src/test/java/codility/p03_time_complexity/TapeEquilibriumTest.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
package codility.p03_time_complexity; | ||
|
||
import org.junit.jupiter.api.BeforeEach; | ||
import org.junit.jupiter.api.Test; | ||
|
||
import static org.assertj.core.api.Assertions.assertThat; | ||
|
||
public class TapeEquilibriumTest { | ||
|
||
TapeEquilibrium tapeEquilibrium; | ||
|
||
@BeforeEach | ||
public void init() { | ||
tapeEquilibrium = new TapeEquilibrium(); | ||
} | ||
|
||
@Test | ||
public void sample1() { | ||
int minimalDifference = tapeEquilibrium.solution(new int[]{3, 1, 2, 4, 3}); | ||
assertThat(minimalDifference).isEqualTo(1); | ||
} | ||
|
||
} |