[LeetCode] Left and Right Sum Differences

2574. Left and Right Sum Differences

Given a 0-indexed integer array nums, find a 0-indexed integer array answer where:

  • answer.length == nums.length.
  • answer[i] = |leftSum[i] - rightSum[i]|.

Where:

  • leftSum[i] is the sum of elements to the left of the index i in the array nums. If there is no such element, leftSum[i] = 0.
  • rightSum[i] is the sum of elements to the right of the index i in the array nums. If there is no such element, rightSum[i] = 0.

Return the array answer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
vector<int> leftRigthDifference(vector<int>& nums) {
int n = nums.size();
vector<int> l(n), r(n);
for(int i = 1; i < n; i++) {
l[i] = l[i-1] + nums[i-1];
}
for(int i = n - 2; i >= 0; i--) {
r[i] = r[i+1] + nums[i+1];
}
vector<int> res(n);
for(int i = 0; i < n; i++) {
res[i] = abs(l[i]-r[i]);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/02/26/PS/LeetCode/left-and-right-sum-differences/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.