930.BinarySubarraysWithSum
Description:
Given a binary array nums and an integer goal, return the number of non-empty subarrays with a sum goal.
A subarray is a contiguous part of the array.
Example 1:
Input: nums = [1,0,1,0,1], goal = 2
Output: 4
Explanation: The 4 subarrays are bolded and underlined below:
[1,0,1,0,1]
[1,0,1,0,1]
[1,0,1,0,1]
[1,0,1,0,1]
Solution:
Prefix sums + Map solution
Explanation:
- We subtract the target sum from the current prefix sum to determine if there exists a subarray with the desired sum. This enables us to efficiently count the number of subarrays.
- We initialize the hashmap with
(0, 1)to handle the case wherethe prefix sum equals the targetsum without including any elements from the array. This ensures that subarrays starting from the beginning of the array are also considered.
if P1 + P2 + p3 + p4 + P5 = 10, P1 + P2 = 2, P1 + p2 +p3 + p4 = 2, and goal = 8. then we can find out 10 - 8 = 2, P3 + p4 + p5 and P5 are the two situations of the question.
{{P1 + P2 + P3 + P4}(prefixSum - goal) + p5}(p1+...P5 = prefixSum)
fun numSubarraysWithSum(nums: IntArray, goal: Int): Int {
val prefixMap = mutableMapOf<Int, Int>()
var prefixSum = 0
var count = 0
// when the garget equal the sum of the array
prefixMap[0] = 1
nums.forEach {
prefixSum += it
count += prefixMap[prefixSum - goal]?:0
prefixMap[prefixSum] = (prefixMap[prefixSum]?:0) + 1
}
return count
}
525.Contiguous Array
Description:
Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1.
Example 1:
Input: nums = [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with an equal number of 0 and 1.
Solution: Efficient kotlin w/map| O(n) time, O(n)space
This question is very like the question 930, but there are two numbers here. So we can use the count to show the different number of 0s and 1s. In such a parameter, we can statistic the count of two numbers in a variable.
fun findMaxLength(nums: IntArray): Int {
val prefixMap = mutableMapOf<Int, Int>()
var maxLength = 0
var count = 0
// in case of 0s and 1s have the same numbers in the array.
prefixMap[0] = -1
nums.forEachIndexed { index, item ->
if (item == 0) {
count--
} else {
count++
}
if (prefixMap.contains(count)) {
val length = index - prefixMap.getOrDefault(count, 0)
maxLength = max(maxLength, length)
} else {
// only record the leftest index, because the question need a longest distance.
prefixMap[count] = index
}
}
return maxLength
}