To efficiently compute the left and right sums for each index, we can use prefix sums. By precomputing the total sum and iterating through the array, we can update left and right sums in a single pass.
classSolution {
public: vector<int> leftRightDifference(vector<int>& nums) {
int n = nums.size();
vector<int> ans(n);
int total =0, left =0;
for (int x : nums) total += x;
for (int i =0; i < n; ++i) {
int right = total - left - nums[i];
ans[i] = abs(left - right);
left += nums[i];
}
return ans;
}
};
classSolution {
publicint[]leftRightDifference(int[] nums) {
int n = nums.length, total = 0, left = 0;
int[] ans =newint[n];
for (int x : nums) total += x;
for (int i = 0; i < n; i++) {
int right = total - left - nums[i];
ans[i]= Math.abs(left - right);
left += nums[i];
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
funleftRightDifference(nums: IntArray): IntArray {
val n = nums.size
val ans = IntArray(n)
var total = nums.sum()
var left = 0for (i in nums.indices) {
val right = total - left - nums[i]
ans[i] = kotlin.math.abs(left - right)
left += nums[i]
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution:
defleftRightDifference(self, nums: list[int]) -> list[int]:
n = len(nums)
ans = [0] * n
total = sum(nums)
left =0for i, x in enumerate(nums):
right = total - left - x
ans[i] = abs(left - right)
left += x
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
impl Solution {
pubfnleft_right_difference(nums: Vec<i32>) -> Vec<i32> {
let n = nums.len();
letmut ans =vec![0; n];
let total: i32= nums.iter().sum();
letmut left =0;
for (i, &x) in nums.iter().enumerate() {
let right = total - left - x;
ans[i] = (left - right).abs();
left += x;
}
ans
}
}