Medium
You are given an integer array nums.
A non-empty subarrays of nums is called centered if the sum of its elements is equal to at least one element within that same subarray.
Return the number of centered subarrays of nums.
Example 1:
Input: nums = [-1,1,0]
Output: 5
Explanation:
[-1], [1], [0]) are centered.[1, 0] has a sum of 1, which is present in the subarray.[-1, 1, 0] has a sum of 0, which is present in the subarray.Example 2:
Input: nums = [2,-3]
Output: 2
Explanation:
Only single-element subarrays ([2], [-3]) are centered.
Constraints:
1 <= nums.length <= 500-105 <= nums[i] <= 105class Solution {
fun centeredSubarrays(nums: IntArray): Int {
val n = nums.size
var result = 0
for (i in 0..<n) {
var subsum = 0
val subnums: MutableSet<Int?> = HashSet<Int?>()
for (j in i..<n) {
subsum += nums[j]
subnums.add(nums[j])
result += if (subnums.contains(subsum)) 1 else 0
}
}
return result
}
}