diff --git a/src/main/java/leetcode/easy/LeftAndRightSumDifferences.java b/src/main/java/leetcode/easy/LeftAndRightSumDifferences.java new file mode 100644 index 0000000..15cc044 --- /dev/null +++ b/src/main/java/leetcode/easy/LeftAndRightSumDifferences.java @@ -0,0 +1,33 @@ +package leetcode.easy; + +public class LeftAndRightSumDifferences { + + int[] leftRightDifference(int[] nums) { + + int rightSum = 0; + int leftSum = 0; + + // Calculate the total right sum + for (int num : nums) { + rightSum += num; + } + + // Iterate through the array + for (int i = 0; i < nums.length; i++) { + // Get the value at index i + int val = nums[i]; + + // Update the right sum + rightSum -= val; + + // Find the difference + nums[i] = Math.abs(leftSum - rightSum); + + // Update the left sum + leftSum += val; + } + + return nums; + } + +} diff --git a/src/test/java/leetcode/easy/LeftAndRightSumDifferencesTest.java b/src/test/java/leetcode/easy/LeftAndRightSumDifferencesTest.java new file mode 100644 index 0000000..8a974b3 --- /dev/null +++ b/src/test/java/leetcode/easy/LeftAndRightSumDifferencesTest.java @@ -0,0 +1,49 @@ +package leetcode.easy; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class LeftAndRightSumDifferencesTest { + + private final LeftAndRightSumDifferences leftAndRightSumDifferences; + + LeftAndRightSumDifferencesTest() { + leftAndRightSumDifferences = new LeftAndRightSumDifferences(); + } + + @Test + void testLeftRightDifference1() { + int[] nums = {10, 4, 8, 3}; + int[] expected = {15, 1, 11, 22}; + assertArrayEquals(expected, leftAndRightSumDifferences.leftRightDifference(nums)); + } + + @Test + void testLeftRightDifference2() { + int[] nums = {4, 2, 1, 3}; + int[] expected = {6, 0, 3, 7}; + assertArrayEquals(expected, leftAndRightSumDifferences.leftRightDifference(nums)); + } + + @Test + void testLeftRightDifference3() { + int[] nums = {1, 2, 3, 4}; + int[] expected = {9, 6, 1, 6}; + assertArrayEquals(expected, leftAndRightSumDifferences.leftRightDifference(nums)); + } + + @Test + void testLeftRightDifference4() { + int[] nums = {1, 1, 1, 1}; + int[] expected = {3, 1, 1, 3}; + assertArrayEquals(expected, leftAndRightSumDifferences.leftRightDifference(nums)); + } + + @Test + void testLeftRightDifference5() { + int[] nums = {1}; + int[] expected = {0}; + assertArrayEquals(expected, leftAndRightSumDifferences.leftRightDifference(nums)); + } +} \ No newline at end of file