summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--AlgoDesignAndTechniqueEdxJava/sources/Partition3.java63
-rw-r--r--AlgoDesignAndTechniqueEdxJava/tests/Partition3Test.java25
2 files changed, 88 insertions, 0 deletions
diff --git a/AlgoDesignAndTechniqueEdxJava/sources/Partition3.java b/AlgoDesignAndTechniqueEdxJava/sources/Partition3.java
new file mode 100644
index 0000000..546fcb2
--- /dev/null
+++ b/AlgoDesignAndTechniqueEdxJava/sources/Partition3.java
@@ -0,0 +1,63 @@
+import java.util.Scanner;
+
+public class Partition3 {
+
+ public static void main(String[] args) {
+ Scanner scanner = new Scanner(System.in);
+ int n = scanner.nextInt();
+ int[] A = new int[n];
+ for (int i = 0; i < n; i++) {
+ A[i] = scanner.nextInt();
+ }
+ System.out.println(partition3(A));
+ }
+
+ public static int partition3(int[] a) {
+ if (a.length < 3)
+ return 0;
+ int sum = 0;
+ for (int i = 0; i < a.length; i++) {
+ sum = sum + a[i];
+ }
+ if (sum % 3 != 0)
+ return 0;
+ int W = sum / 3;
+ int[][] values = optimalWeight2DArray(W, a);
+ int count = 0;
+ for (int i = 1; i < a.length + 1; i++) {
+ for (int w = 1; w < W + 1; w++) {
+ if (values[w][i] == W)
+ count = count + 1;
+ }
+ }
+ if (count >= 3)
+ return 1;
+ else
+ return 0;
+ }
+
+ public static int[][] optimalWeight2DArray(int W, int[] w2) {
+ int j = w2.length;
+ int[][] value = new int[W + 1][j + 1];
+
+ for (int i = 0; i < j + 1; i++) {
+ for (int w = 0; w < W + 1; w++) {
+ if (i == 0 || w == 0) {
+ value[w][i] = 0;
+ continue;
+ }
+ value[w][i] = value[w][i - 1];
+ if (w2[i - 1] <= w) {
+ int val = value[w - w2[i - 1]][i - 1] + w2[i - 1];
+ if (value[w][i] < val) {
+ value[w][i] = val;
+ }
+ }
+ }
+
+ }
+
+ return value;
+ }
+
+}
diff --git a/AlgoDesignAndTechniqueEdxJava/tests/Partition3Test.java b/AlgoDesignAndTechniqueEdxJava/tests/Partition3Test.java
new file mode 100644
index 0000000..593d21a
--- /dev/null
+++ b/AlgoDesignAndTechniqueEdxJava/tests/Partition3Test.java
@@ -0,0 +1,25 @@
+import static org.junit.jupiter.api.Assertions.*;
+
+import org.junit.jupiter.api.Test;
+
+class Partition3Test {
+
+ @Test
+ void test() {
+ int[] a = {3, 3, 3, 3};
+ assertEquals(0, Partition3.partition3(a));
+ }
+
+ @Test
+ void test1() {
+ int[] a = {30};
+ assertEquals(0, Partition3.partition3(a));
+ }
+
+ @Test
+ void test2() {
+ int[] a = {1, 2, 3, 4, 5, 5, 7, 7, 8, 10, 12, 19, 25};
+ assertEquals(1, Partition3.partition3(a));
+ }
+
+}