diff --git a/1590. Make Sum Divisible by P 1 b/1590. Make Sum Divisible by P 1 new file mode 100644 index 0000000..b3f2669 --- /dev/null +++ b/1590. Make Sum Divisible by P 1 @@ -0,0 +1,37 @@ +class Solution { +public: + int minSubarray(vector& nums, int p) { + long long sufsum = 0; + for (auto x : nums) { + sufsum += x; + } + + long long presum = 0; + int n = nums.size(); + int ans = n; + unordered_map dp; + + // "Virtual" prefix: sum 0 at index -1 (empty prefix) + dp[0] = -1; + + for (int i = 0; i < n; i++) { + presum += nums[i]; // extend prefix + sufsum -= nums[i]; // shrink suffix + + // Store the latest index with this prefix remainder + dp[presum % p] = i; + + // Right remainder and required left remainder + int rem = (p - sufsum % p) % p; + + // If we have some prefix with this remainder, + // try removing between it and i + if (dp.find(rem) != dp.end()) { + ans = min(ans, i - dp[rem]); + } + } + + if (ans == n) return -1; + return ans; + } +};