Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 4b23891

Browse files
committedApr 20, 2025
Add solution #1590
1 parent 33c223e commit 4b23891

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed
 

‎README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,388 LeetCode solutions in JavaScript
1+
# 1,389 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -1213,6 +1213,7 @@
12131213
1585|[Check If String Is Transformable With Substring Sort Operations](./solutions/1585-check-if-string-is-transformable-with-substring-sort-operations.js)|Hard|
12141214
1588|[Sum of All Odd Length Subarrays](./solutions/1588-sum-of-all-odd-length-subarrays.js)|Easy|
12151215
1589|[Maximum Sum Obtained of Any Permutation](./solutions/1589-maximum-sum-obtained-of-any-permutation.js)|Medium|
1216+
1590|[Make Sum Divisible by P](./solutions/1590-make-sum-divisible-by-p.js)|Medium|
12161217
1598|[Crawler Log Folder](./solutions/1598-crawler-log-folder.js)|Easy|
12171218
1657|[Determine if Two Strings Are Close](./solutions/1657-determine-if-two-strings-are-close.js)|Medium|
12181219
1668|[Maximum Repeating Substring](./solutions/1668-maximum-repeating-substring.js)|Easy|
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* 1590. Make Sum Divisible by P
3+
* https://leetcode.com/problems/make-sum-divisible-by-p/
4+
* Difficulty: Medium
5+
*
6+
* Given an array of positive integers nums, remove the smallest subarray (possibly empty) such that
7+
* the sum of the remaining elements is divisible by p. It is not allowed to remove the whole array.
8+
*
9+
* Return the length of the smallest subarray that you need to remove, or -1 if it's impossible.
10+
*
11+
* A subarray is defined as a contiguous block of elements in the array.
12+
*/
13+
14+
/**
15+
* @param {number[]} nums
16+
* @param {number} p
17+
* @return {number}
18+
*/
19+
var minSubarray = function(nums, p) {
20+
const totalSum = nums.reduce((sum, num) => sum + num, 0);
21+
const remainder = totalSum % p;
22+
23+
if (remainder === 0) return 0;
24+
25+
const prefixSums = new Map([[0, -1]]);
26+
let currentSum = 0;
27+
let minLength = nums.length;
28+
29+
for (let i = 0; i < nums.length; i++) {
30+
currentSum = (currentSum + nums[i]) % p;
31+
const target = (currentSum - remainder + p) % p;
32+
33+
if (prefixSums.has(target)) {
34+
minLength = Math.min(minLength, i - prefixSums.get(target));
35+
}
36+
37+
prefixSums.set(currentSum, i);
38+
}
39+
40+
return minLength < nums.length ? minLength : -1;
41+
};

0 commit comments

Comments
 (0)
Please sign in to comment.