Skip to content

Commit 263e0d8

Browse files
add a solution for 1695
1 parent 9f46e09 commit 263e0d8

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

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

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

3+
import java.util.HashMap;
34
import java.util.HashSet;
5+
import java.util.Map;
46
import java.util.Set;
57

68
public class _1695 {
@@ -26,4 +28,29 @@ public int maximumUniqueSubarray(int[] nums) {
2628
return maxSum;
2729
}
2830
}
31+
32+
public static class Solution2 {
33+
/**
34+
* My completely original solution on 10/202/2021. Classic sliding window solution.
35+
*/
36+
public int maximumUniqueSubarray(int[] nums) {
37+
Map<Integer, Integer> map = new HashMap<>();
38+
int sum = 0;
39+
int start = 0;
40+
int ans = 0;
41+
for (int i = 0; i < nums.length; i++) {
42+
if (map.containsKey(nums[i])) {
43+
Integer lastIndex = map.get(nums[i]);
44+
while (start <= lastIndex) {
45+
sum -= nums[start];
46+
start++;
47+
}
48+
}
49+
sum += nums[i];
50+
map.put(nums[i], i);
51+
ans = Math.max(ans, sum);
52+
}
53+
return ans;
54+
}
55+
}
2956
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package com.fishercoder;
2+
3+
import com.fishercoder.solutions._1695;
4+
import org.junit.BeforeClass;
5+
import org.junit.Test;
6+
7+
import static org.junit.Assert.assertEquals;
8+
9+
public class _1695Test {
10+
private static _1695.Solution1 solution1;
11+
private static _1695.Solution2 solution2;
12+
private static int[] nums;
13+
private static int expected;
14+
15+
@BeforeClass
16+
public static void setup() {
17+
solution1 = new _1695.Solution1();
18+
solution2 = new _1695.Solution2();
19+
}
20+
21+
@Test
22+
public void test1() {
23+
nums = new int[]{4, 2, 4, 5, 6};
24+
expected = 17;
25+
assertEquals(expected, solution1.maximumUniqueSubarray(nums));
26+
assertEquals(expected, solution2.maximumUniqueSubarray(nums));
27+
}
28+
29+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy