프로그래밍/알고리즘

[LeetCode] 2574. Left and Right Sum Differences

노란구슬 2026. 5. 19. 22:58
728x90
반응형

2574. Left and Right Sum Differences

LeetCode

https://leetcode.com/problems/left-and-right-sum-differences/description/

 

Left and Right Sum Differences - LeetCode

Can you solve this real interview question? Left and Right Sum Differences - You are given a 0-indexed integer array nums of size n. Define two arrays leftSum and rightSum where: * leftSum[i] is the sum of elements to the left of the index i in the array n

leetcode.com

 

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

Define two arrays leftSum and rightSum 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 an integer array answer of size n where answer[i] = |leftSum[i] - rightSum[i]|.

크기가 n인 0-인덱스 정수 배열 nums가 주어집니다.

다음과 같이 두 배열 leftSum과 rightSum을 정의합니다.
- leftSum[i]는 배열 nums에서 인덱스 i의 왼쪽에 있는 원소들의 합입니다. 만약 왼쪽에 원소가 없다면 leftSum[i] = 0입니다.
- rightSum[i]는 배열 nums에서 인덱스 i의 오른쪽에 있는 원소들의 합입니다. 만약 오른쪽에 원소가 없다면 rightSum[i] = 0입니다.

answer[i] = |leftSum[i] - rightSum[i]|를 만족하는 크기가 n인 정수 배열 answer를 반환하세요. (단, |x|는 x의 절대값입니다.)

 

Example

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]
Input: nums = [1]
Output: [0]
Explanation: The array leftSum is [0] and the array rightSum is [0].
The array answer is [|0 - 0|] = [0]. 

1. 문제 요구사항 분석

왼쪽합과 오른쪽 방향 합을 각각 더한 후, 왼쪽합에서 오른쪽 합을 뺀 절댓값을 구하는 문제

2. 접근 전략

😁 누적합 문제로 풀기

왼쪽합 따로, 오른쪽합 따로 누적합을 구한 후,

왼쪽합에서 오른쪽 합을 뺀 절댓값 구하기

import java.util.*;

class Solution {
    public int[] leftRightDifference(int[] nums) {
        int n = nums.length;
        int[] leftSum = new int[n];
        int[] rightSum = new int[n];
        int[] answer = new int[n];

        for (int i = 1; i < n; i++) {
            // 왼쪽 누적합
            leftSum[i] = leftSum[i - 1] + nums[i - 1];
            // 오른쪽 누적합
            rightSum[n - 1 - i] = rightSum[n - i] + nums[n - i];
        }

        // 빼기
        for (int i = 0; i < n; i++) {
            answer[i] = Math.abs(leftSum[i] - rightSum[i]);
        }

        return answer;
    }
}



728x90
반응형