algoadvance

Leetcode 2894. Divisible and Non Sure! Let’s solve the LeetCode problem step-by-step. Here’s a structured approach:

Problem Statement

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.

Clarifying Questions

  1. Can nums contain negative numbers?
    • Yes, the problem statement does not restrict the nature of the integers.
  2. What should we return if all numbers are divisible or non-divisible by k?
    • Follow the same logic: sum the elements that match the condition and return the difference.

Strategy

  1. Initialize two variables divisible_sum and non_divisible_sum to zero.
  2. Iterate through each element in nums and:
    • If the element is divisible by k, add it to divisible_sum.
    • Otherwise, add it to non_divisible_sum.
  3. Compute and return the difference: divisible_sum - non_divisible_sum.

Code

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;
    }
}

Time Complexity

This approach ensures we efficiently calculate the required difference with optimal time and space usage.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI