Skip to content

Commit

Permalink
Left and Right sum differences
Browse files Browse the repository at this point in the history
  • Loading branch information
nikoo28 committed Oct 26, 2024
1 parent e22afbc commit f9b2f57
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 0 deletions.
33 changes: 33 additions & 0 deletions src/main/java/leetcode/easy/LeftAndRightSumDifferences.java
Original file line number Diff line number Diff line change
@@ -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;
}

}
49 changes: 49 additions & 0 deletions src/test/java/leetcode/easy/LeftAndRightSumDifferencesTest.java
Original file line number Diff line number Diff line change
@@ -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));
}
}

0 comments on commit f9b2f57

Please sign in to comment.