LeetCode 2535: Difference Between Element Sum and Digit Sum of an Array

ArrayMath

Problem Description

Explanation:

  • To solve this problem, we need to calculate the element sum and digit sum of the given array.
  • We can iterate through the array to calculate the element sum.
  • To calculate the digit sum, we iterate through each number in the array, convert it to a string, and then sum up all the digits in each number.
  • Finally, we return the absolute difference between the element sum and digit sum.

Time Complexity: O(n) where n is the number of elements in the array. Space Complexity: O(1) since we are using a constant amount of extra space.

:

Solutions

class Solution {
    public int subtractProductAndSum(int n) {
        int elementSum = 0, digitSum = 0;
        for (int num : nums) {
            elementSum += num;
            String numStr = String.valueOf(num);
            for (int i = 0; i < numStr.length(); i++) {
                digitSum += numStr.charAt(i) - '0';
            }
        }
        return Math.abs(elementSum - digitSum);
    }
}

Loading editor...