-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Solution.java
50 lines (41 loc) · 1.34 KB
/
Solution.java
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
// github.com/RodneyShag
import java.util.Scanner;
// Idea: Use a "sliding window" of "m" squares. Each time we add a square to the right, remove one from the left.
// Time Complexity: O(n)
// Space Complexity: O(1) (other than saving input)
public class Solution {
static int solve(int n, int[] square, int d, int m) {
int sum = 0;
int numWays = 0;
/* Test first set of "m" chocolates */
for (int i = 0; i < m; i++) {
sum += square[i];
}
if (sum == d) {
numWays++;
}
/* Test remaining sets of "m" chocolates */
for (int i = m; i < square.length; i++) {
sum += square[i] - square[i-m]; // add chocolate, remove chocolate
if (sum == d) {
numWays++;
}
}
return numWays;
}
public static void main(String[] args) {
/* Save input */
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[] square = new int[n];
for (int i = 0; i < n; i++) {
square[i] = scan.nextInt();
}
int d = scan.nextInt();
int m = scan.nextInt();
scan.close();
/* Calculate result */
int result = solve(n, square, d, m);
System.out.println(result);
}
}