Leetcode 2535. Difference Between Element Sum and Digit Sum of an Array
Given an integer array nums
, you need to compute:
The task is to return the absolute difference between the elementSum and the digitSum.
elementSum
by iterating through the array and summing all elements.digitSum
by iterating through the array, converting each element to its absolute value, iterating through its digits, and summing these digits.elementSum
and digitSum
.Here’s the C++ code to solve the problem:
#include <vector>
#include <cmath> // For std::abs
int differenceOfSum(const std::vector<int>& nums) {
int elementSum = 0;
int digitSum = 0;
for (int num : nums) {
elementSum += num;
int absNum = std::abs(num);
while (absNum > 0) {
digitSum += absNum % 10;
absNum /= 10;
}
}
return std::abs(elementSum - digitSum);
}
The time complexity of this solution is (O(n \cdot k)), where:
Given the constraints (elements range from -1,000,000 to 1,000,000), (k) can be considered as a constant (since it would be around 6-7 digits for most cases), making the overall complexity close to (O(n)).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?