Leetcode 2894. Divisible and Non Sure! Let’s solve the LeetCode problem step-by-step. Here’s a structured approach:
You are given an array of integers nums and an integer k. Return the sum of elements that are divisible by k minus the sum of elements that are not divisible by k.
nums contain negative numbers?
k?
divisible_sum and non_divisible_sum to zero.nums and:
k, add it to divisible_sum.non_divisible_sum.divisible_sum - non_divisible_sum.public class Solution {
public int getDifference(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;
}
}
n is the number of elements in nums. The algorithm iterates through each element once.This approach ensures we efficiently calculate the required difference with optimal time and space usage.
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?