diff options
author | Haidong Ji | 2018-09-07 20:59:25 -0500 |
---|---|---|
committer | Haidong Ji | 2018-09-07 20:59:25 -0500 |
commit | aa32f7835fa2776e29fb42c3bdac06ab1f489d0f (patch) | |
tree | 9b858cd4949143c9e12473d46f3ddfba1d9dd48c | |
parent | 29e054f5ebf164d53319c0bdb348db421f98b942 (diff) |
Max Dot Product done.
I wasn't just a little surprised how simple it is.
-rw-r--r-- | AlgoDesignAndTechniqueEdxJava/sources/MaxDotProd.java | 30 | ||||
-rw-r--r-- | AlgoDesignAndTechniqueEdxJava/tests/MaxDotProdTest.java | 28 |
2 files changed, 58 insertions, 0 deletions
diff --git a/AlgoDesignAndTechniqueEdxJava/sources/MaxDotProd.java b/AlgoDesignAndTechniqueEdxJava/sources/MaxDotProd.java new file mode 100644 index 0000000..77672aa --- /dev/null +++ b/AlgoDesignAndTechniqueEdxJava/sources/MaxDotProd.java @@ -0,0 +1,30 @@ +import java.util.Arrays; +import java.util.Scanner; + +public class MaxDotProd { + + 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(); + } + int[] b = new int[n]; + for (int i = 0; i < n; i++) { + b[i] = scanner.nextInt(); + } + System.out.println(getMaxDotProduct(a, b)); + } + + public static long getMaxDotProduct(int[] a, int[] b) { + Arrays.sort(a); + Arrays.sort(b); + long result = 0; + for (int i = 0; i < b.length; i++) { + result = (long) a[i] * b[i] + result; + } + return result; + } + +} diff --git a/AlgoDesignAndTechniqueEdxJava/tests/MaxDotProdTest.java b/AlgoDesignAndTechniqueEdxJava/tests/MaxDotProdTest.java new file mode 100644 index 0000000..888967b --- /dev/null +++ b/AlgoDesignAndTechniqueEdxJava/tests/MaxDotProdTest.java @@ -0,0 +1,28 @@ +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; + +class MaxDotProdTest { + + @Test + void test() { + int[] a = new int[] { 60, 100, 120 }; + int[] b = new int[] { 20, 50, 30 }; + assertEquals(10200, MaxDotProd.getMaxDotProduct(a, b)); + } + + @Test + void test1() { + int[] a = new int[] { 23}; + int[] b = new int[] { 39 }; + assertEquals(897, MaxDotProd.getMaxDotProduct(a, b)); + } + + @Test + void test2() { + int[] a = new int[] { 1,3,-5}; + int[] b = new int[] { -2,4,1 }; + assertEquals(23, MaxDotProd.getMaxDotProduct(a, b)); + } + +} |