-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC1590.java
More file actions
71 lines (50 loc) · 1.47 KB
/
LC1590.java
File metadata and controls
71 lines (50 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
* LC1590
*/
import java.util.*;
public class LC1590 {
public static int minSubarray(int[] nums, int p) {
int totalSum = 0;
for (int i = 0; i < nums.length; i++) {
totalSum = (totalSum + nums[i]) % p;
}
if (totalSum == 0) {
return 0;
}
int sumJ = 0;
Map<Integer, Integer> map = new HashMap<>();
map.put(0, -1);
int min = nums.length;
for (int i = 0; i < nums.length; i++) {
sumJ = (sumJ + nums[i]) % p;
int sumI = (sumJ - totalSum + p) % p;
if (map.containsKey(sumI)) {
min = Math.min(min, i - map.get(sumI));
}
map.put(sumJ, i);
}
if (min == nums.length) {
return -1;
}
return min;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Array Size : ");
int size = sc.nextInt();
System.out.println();
int arr[] = new int[size];
System.out.println("Enter Array Elements : ");
for (int i = 0; i < arr.length; i++) {
System.out.printf("[%d] : ", i);
arr[i] = sc.nextInt();
}
System.out.println();
System.out.print("Enter Element P : ");
int p = sc.nextInt();
System.out.println();
int ans = minSubarray(arr, p);
System.out.println(ans);
sc.close();
}
}