[코테 풀이] Left and Right Sum Differences

시내·2024년 6월 12일
0

Q_2574) Left and Right Sum Differences

출처 : https://leetcode.com/problems/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.

class Solution {
    public int[] leftRightDifference(int[] nums) {
        int[] leftSum = new int[nums.length];
        int[] rightSum = new int[nums.length];
        int[] total = new int[nums.length];
        int leftInd = 0;
        int righttInd = 0;
        int tInd = 0;
        int left = 0;
        int right = 1;
        while (left < nums.length) {
            for (int l = 0; l < left; l++) {
                leftSum[leftInd] += nums[l];
            }
            left++;
            leftInd++;
        }

        while (right < nums.length) {
            for (int r = right; r < nums.length; r++) {
                rightSum[righttInd] += nums[r];
            }
            right++;
            righttInd++;
        }
        for (int t = 0; t < nums.length; t++) {
            total[tInd++] = Math.abs(rightSum[t] - leftSum[t]);
        }
        return total;
    }
}
profile
contact 📨 ksw08215@gmail.com

0개의 댓글