From fa8ffeeeddafc69032602ccce0b9f0846a65afb5 Mon Sep 17 00:00:00 2001 From: Abhishek Tripathi <42455093+abhishektripathi66@users.noreply.github.com> Date: Thu, 3 Oct 2024 20:20:25 +0530 Subject: [PATCH] Create MakeSumDivisible.java --- Leetcode/MakeSumDivisible.java | 48 ++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Leetcode/MakeSumDivisible.java diff --git a/Leetcode/MakeSumDivisible.java b/Leetcode/MakeSumDivisible.java new file mode 100644 index 0000000..ee622ae --- /dev/null +++ b/Leetcode/MakeSumDivisible.java @@ -0,0 +1,48 @@ +/** +1590. Make Sum Divisible by P +Solved +Medium +Topics +Companies +Hint +Given an array of positive integers nums, remove the smallest subarray (possibly empty) such that the sum of the remaining elements is divisible by p. It is not allowed to remove the whole array. + +Return the length of the smallest subarray that you need to remove, or -1 if it's impossible. + +A subarray is defined as a contiguous block of elements in the array. + + **/ + +import java.util.HashMap; + +class MakeSumDivisible { + public int minSubarray(int[] nums, int p) { + long totalSum = 0; + for (int num : nums) { + totalSum += num; + } + + // Find remainder when total sum is divided by p + int rem = (int)(totalSum % p); + if (rem == 0) return 0; // If remainder is 0, no subarray needs to be removed + + HashMap prefixMod = new HashMap<>(); + prefixMod.put(0, -1); // Initialize to handle full prefix + long prefixSum = 0; + int minLength = nums.length; + + for (int i = 0; i < nums.length; ++i) { + prefixSum += nums[i]; + int currentMod = (int)(prefixSum % p); + int targetMod = (currentMod - rem + p) % p; + + if (prefixMod.containsKey(targetMod)) { + minLength = Math.min(minLength, i - prefixMod.get(targetMod)); + } + + prefixMod.put(currentMod, i); + } + + return minLength == nums.length ? -1 : minLength; + } +}