Skip to content

Commit

Permalink
update 560 java, cheatsheet
Browse files Browse the repository at this point in the history
  • Loading branch information
yennanliu committed Dec 14, 2024
1 parent b26215c commit 8b0f6d6
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 3 deletions.
47 changes: 46 additions & 1 deletion doc/cheatsheet/prefix_sum.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ We can use prefix sums. Say P[i+1] = A[0] + A[1] + ... + A[i], where A[i] = 1 if
- LC 370
- sub array
- sum array sum == k
- pre sum count
- LC 560
- Maximum Size Subarray Sum Equals k
- LC 325
Expand Down Expand Up @@ -225,7 +226,51 @@ class Solution(object):
return result
```

### 2-5) Continuous Subarray Sum
### 2-5) Subarray Sum Equals K

```java
// java
// LC 560
public int subarraySum(int[] nums, int k) {
/**
* NOTE !!!
*
* use Map to store prefix sum and its count
*
* map : {prefixSum: count}
*
*
* -> since "same preSum may have multiple combination" within hashMap,
* so it's needed to track preSum COUNT, instead of its index
*/
Map<Integer, Integer> map = new HashMap<>();
int presum = 0;
int count = 0;

/**
* NOTE !!!
*
* Initialize the map with prefix sum 0 (to handle subarrays starting at index 0)
*/
map.put(0, 1);

for (int num : nums) {
presum += num;

// Check if there's a prefix sum such that presum - k exists
if (map.containsKey(presum - k)) {
count += map.get(presum - k);
}

// Update the map with the current prefix sum
map.put(presum, map.getOrDefault(presum, 0) + 1);
}

return count;
}
```

### 2-6) Continuous Subarray Sum

```java
// java
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,26 @@ public class SubarraySumEqualsK {
* • Removed unnecessary index-based conditions (map.get(presum - k) == i + 1) which were incorrect and not required for this problem.
*/
public int subarraySum(int[] nums, int k) {
// Map to store prefix sum and its count
/**
* NOTE !!!
*
* use Map to store prefix sum and its count
*
* map : {prefixSum: count}
*
*
* -> since "same preSum may have multiple combination" within hashMap,
* so it's needed to track preSum COUNT, instead of its index
*/
Map<Integer, Integer> map = new HashMap<>();
int presum = 0;
int count = 0;

// Initialize the map with prefix sum 0 (to handle subarrays starting at index 0)
/**
* NOTE !!!
*
* Initialize the map with prefix sum 0 (to handle subarrays starting at index 0)
*/
map.put(0, 1);

for (int num : nums) {
Expand Down

0 comments on commit 8b0f6d6

Please sign in to comment.