algoadvance

Leetcode 2894. Divisible and Non

Problem Statement

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.

Clarifying Questions

  1. Can the input array contain negative numbers?
    • Yes, the array can contain negative numbers.
  2. What should be the output if the array is empty?
    • If the array is empty, the output should be 0.
  3. Can k be zero?
    • No, k will always be a non-zero integer.
  4. What is the range of the integers in the array?
    • The elements in the array and the value of k can be within the typical range of 32-bit integers.

Strategy

  1. Initialize two variables to store the sums:
    • divisible_sum for elements divisible by k.
    • non_divisible_sum for elements not divisible by k.
  2. Traverse through each element of the array:
    • If the element is divisible by k, add it to divisible_sum.
    • Otherwise, add it to non_divisible_sum.
  3. Return the difference between divisible_sum and non_divisible_sum.

Code

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

Time Complexity

This solution is efficient and straightforward, handling negative numbers and various edge cases as well.

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