Leetcode 2894. Divisible and Non
Given an integer array nums
and an integer k
, return the sum of the elements in the array that are divisible by k
, minus the sum of the elements in the array that are not divisible by k
.
0
.k
be zero?
k
will always be a non-zero integer.k
can be within the typical range of 32-bit integers.divisible_sum
for elements divisible by k
.non_divisible_sum
for elements not divisible by k
.k
, add it to divisible_sum
.non_divisible_sum
.divisible_sum
and non_divisible_sum
.#include <vector>
int sumDifference(const std::vector<int>& nums, int k) {
int divisible_sum = 0;
int non_divisible_sum = 0;
for (int num : nums) {
if (num % k == 0) {
divisible_sum += num;
} else {
non_divisible_sum += num;
}
}
return divisible_sum - non_divisible_sum;
}
nums
. This is because we are traversing the array once to compute the sums.This solution is efficient and straightforward, handling negative numbers and various edge cases as well.
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?