Skip to content

Commit 8b0f6d6

Browse files
committed
update 560 java, cheatsheet
1 parent b26215c commit 8b0f6d6

File tree

2 files changed

+62
-3
lines changed

2 files changed

+62
-3
lines changed

doc/cheatsheet/prefix_sum.md

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ We can use prefix sums. Say P[i+1] = A[0] + A[1] + ... + A[i], where A[i] = 1 if
2828
- LC 370
2929
- sub array
3030
- sum array sum == k
31+
- pre sum count
3132
- LC 560
3233
- Maximum Size Subarray Sum Equals k
3334
- LC 325
@@ -225,7 +226,51 @@ class Solution(object):
225226
return result
226227
```
227228

228-
### 2-5) Continuous Subarray Sum
229+
### 2-5) Subarray Sum Equals K
230+
231+
```java
232+
// java
233+
// LC 560
234+
public int subarraySum(int[] nums, int k) {
235+
/**
236+
* NOTE !!!
237+
*
238+
* use Map to store prefix sum and its count
239+
*
240+
* map : {prefixSum: count}
241+
*
242+
*
243+
* -> since "same preSum may have multiple combination" within hashMap,
244+
* so it's needed to track preSum COUNT, instead of its index
245+
*/
246+
Map<Integer, Integer> map = new HashMap<>();
247+
int presum = 0;
248+
int count = 0;
249+
250+
/**
251+
* NOTE !!!
252+
*
253+
* Initialize the map with prefix sum 0 (to handle subarrays starting at index 0)
254+
*/
255+
map.put(0, 1);
256+
257+
for (int num : nums) {
258+
presum += num;
259+
260+
// Check if there's a prefix sum such that presum - k exists
261+
if (map.containsKey(presum - k)) {
262+
count += map.get(presum - k);
263+
}
264+
265+
// Update the map with the current prefix sum
266+
map.put(presum, map.getOrDefault(presum, 0) + 1);
267+
}
268+
269+
return count;
270+
}
271+
```
272+
273+
### 2-6) Continuous Subarray Sum
229274

230275
```java
231276
// java

leetcode_java/src/main/java/LeetCodeJava/HashTable/SubarraySumEqualsK.java

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,12 +66,26 @@ public class SubarraySumEqualsK {
6666
* • Removed unnecessary index-based conditions (map.get(presum - k) == i + 1) which were incorrect and not required for this problem.
6767
*/
6868
public int subarraySum(int[] nums, int k) {
69-
// Map to store prefix sum and its count
69+
/**
70+
* NOTE !!!
71+
*
72+
* use Map to store prefix sum and its count
73+
*
74+
* map : {prefixSum: count}
75+
*
76+
*
77+
* -> since "same preSum may have multiple combination" within hashMap,
78+
* so it's needed to track preSum COUNT, instead of its index
79+
*/
7080
Map<Integer, Integer> map = new HashMap<>();
7181
int presum = 0;
7282
int count = 0;
7383

74-
// Initialize the map with prefix sum 0 (to handle subarrays starting at index 0)
84+
/**
85+
* NOTE !!!
86+
*
87+
* Initialize the map with prefix sum 0 (to handle subarrays starting at index 0)
88+
*/
7589
map.put(0, 1);
7690

7791
for (int num : nums) {

0 commit comments

Comments
 (0)