Skip to content

Commit c27c731

Browse files
add 1352
1 parent 5143683 commit c27c731

File tree

2 files changed

+28
-10
lines changed

2 files changed

+28
-10
lines changed

src/main/java/com/fishercoder/solutions/_1352.java

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
package com.fishercoder.solutions;
22

3+
import java.util.ArrayList;
4+
import java.util.List;
5+
36
/**
47
* 1352. Product of the Last K Numbers
58
*
@@ -37,18 +40,27 @@
3740
* */
3841
public class _1352 {
3942
public static class Solution1 {
43+
/**credit: https://leetcode.com/problems/product-of-the-last-k-numbers/discuss/510260/JavaC%2B%2BPython-Prefix-Product*/
4044
public static class ProductOfNumbers {
4145

42-
public ProductOfNumbers() {
46+
List<Integer> list;
4347

48+
public ProductOfNumbers() {
49+
add(0);
4450
}
4551

4652
public void add(int num) {
47-
53+
if (num > 0) {
54+
list.add(list.get(list.size() - 1) * num);
55+
} else {
56+
list = new ArrayList<>();
57+
list.add(1);
58+
}
4859
}
4960

5061
public int getProduct(int k) {
51-
return -1;
62+
int size = list.size();
63+
return k >= size ? 0 : (list.get(size - 1) / list.get(size - k - 1));
5264
}
5365
}
5466
}
Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,26 @@
11
package com.fishercoder;
22

33
import com.fishercoder.solutions._1352;
4-
import org.junit.BeforeClass;
54
import org.junit.Test;
65

6+
import static org.junit.Assert.assertEquals;
7+
78
public class _1352Test {
89
private static _1352.Solution1.ProductOfNumbers productOfNumbers;
910

10-
@BeforeClass
11-
public static void setup() {
12-
productOfNumbers = new _1352.Solution1.ProductOfNumbers();
13-
}
14-
1511
@Test
1612
public void test1() {
17-
13+
productOfNumbers = new _1352.Solution1.ProductOfNumbers();
14+
productOfNumbers.add(3);
15+
productOfNumbers.add(0);
16+
productOfNumbers.add(2);
17+
productOfNumbers.add(5);
18+
productOfNumbers.add(4);
19+
assertEquals(20, productOfNumbers.getProduct(2));
20+
assertEquals(40, productOfNumbers.getProduct(3));
21+
assertEquals(0, productOfNumbers.getProduct(4));
22+
productOfNumbers.add(8);
23+
assertEquals(32, productOfNumbers.getProduct(2));
1824
}
1925

2026
}

0 commit comments

Comments
 (0)