Skip to content

Commit b4e6650

Browse files
solves #2574: Left and Right Sum Differences in java
1 parent 35a1739 commit b4e6650

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -803,7 +803,7 @@
803803
| 2562 | [Find the Array Concatenation Value](https://leetcode.com/problems/find-the-array-concatenation-value) | [![Java](assets/java.png)](src/FindTheArrayConcatenationValue.java) | |
804804
| 2566 | [Maximum Difference by Remapping a Digit](https://leetcode.com/problems/maximum-difference-by-remapping-a-digit) | [![Java](assets/java.png)](src/MaximumDifferenceByRemappingADigit.java) | |
805805
| 2570 | [Merge Two 2D Arrays by Summing Values](https://leetcode.com/problems/merge-two-2d-arrays-by-summing-values) | [![Java](assets/java.png)](src/MergeTwo2DArraysBySummingValues.java) | |
806-
| 2574 | [Left and Right Sum Differences](https://leetcode.com/problems/left-and-right-sum-differences) | | |
806+
| 2574 | [Left and Right Sum Differences](https://leetcode.com/problems/left-and-right-sum-differences) | [![Java](assets/java.png)](src/LeftAndRightSumDifferences.java) | |
807807
| 2578 | [Split With Minimum Sum](https://leetcode.com/problems/split-with-minimum-sum) | | |
808808
| 2582 | [Pass the Pillow](https://leetcode.com/problems/pass-the-pillow) | | |
809809
| 2586 | [Count the Number of Vowel Strings in Range](https://leetcode.com/problems/count-the-number-of-vowel-strings-in-range) | | |

src/LeftAndRightSumDifferences.java

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// https://leetcode.com/problems/left-and-right-sum-differences
2+
// T: O(N)
3+
// S: O(N)
4+
5+
public class LeftAndRightSumDifferences {
6+
public int[] leftRightDifference(int[] nums) {
7+
final int[] result = new int[nums.length];
8+
int leftSum = 0, rightSum = sum(nums, 1, nums.length);
9+
10+
for (int index = 0 ; index < nums.length ; index++) {
11+
result[index] = Math.abs(leftSum - rightSum);
12+
leftSum += nums[index];
13+
rightSum -= (index + 1 < nums.length ? nums[index + 1] : 0);
14+
}
15+
16+
return result;
17+
}
18+
19+
private int sum(int[] array, int startIndex, int endIndex) {
20+
int sum = 0;
21+
for (int i = startIndex ; i < endIndex ; i++) {
22+
sum += array[i];
23+
}
24+
return sum;
25+
}
26+
}

0 commit comments

Comments
 (0)