Post

2714 Left And Right Sum Differences

2714 Left And Right Sum Differences

Left and Right Sum Differences image

You are given a 0-indexed integer array nums of size n.

Define two arrays leftSum and rightSum where:

1
2
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 an integer array answer of size n where answer[i] =leftSum[i] - rightSum[i].

 

Example 1:

1
2
3
4
5
6
**Input:** nums = [10,4,8,3]
**Output:** [15,1,11,22]
**Explanation:** The array leftSum is [0,10,14,22] and the array rightSum is [15,11,3,0].
The array answer is [|0 - 15|,|10 - 11|,|14 - 3|,|22 - 0|] = [15,1,11,22].

Example 2:

1
2
3
4
5
6
**Input:** nums = [1]
**Output:** [0]
**Explanation:** The array leftSum is [0] and the array rightSum is [0].
The array answer is [|0 - 0|] = [0].

 

Constraints:

1
2
1 <= nums.length <= 1000
1 <= nums[i] <= 105
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

use std::iter::zip;

impl Solution {
    pub fn left_right_difference(nums: Vec<i32>) -> Vec<i32> {
        let mut left = 0;
        let mut right = 0;
        let mut left_arr = Vec::new();
        let mut right_arr = Vec::new();
        let mut ans = Vec::new();

        for k in &nums {
           left_arr.push(left);
           left += k;
        }
        left_arr.push(left);

        let mut total : i32 = nums.clone().into_iter().sum();
        for k in &nums {
            right += k;
           right_arr.push(total - right);
           
        }

        for (a,b) in zip(left_arr,right_arr) {
            ans.push((a-b).abs());
        }
        ans
        
    }
}



This post is licensed under CC BY 4.0 by the author.