In this post we can see complete solution for the HackerRank Exercise Subarray Division. The problem statement goes like this -
Determine how many ways can divide the chocolate bar (as contiguous segment) between Lily and Ron given condition :
- The length of the segment matches Ron's birth month
- The sum of the integers on the squares is equal to his birth day.
Working solution in Swift given below:
func birthday(s: [Int], d: Int, m: Int) -> Int {
var sCount = 0
var index = 0
// 1
while (index < s.count) {
var dayLength = 0
let limit = index+m > s.count ? s.count : index+m
// 2
for jIndex in index..<limit {
dayLength += s[jIndex]
}
// 3
if dayLength == d {
sCount += 1
}
index += 1
}
// 4
return sCount
}
Explanation:
1. Loop each chocolate segment array element `s` to capture count of instances that matches given 2 conditions.
2. Segment calculated as array limit ranging from current element up to next `m` elements. Also `limit` segment range which can go out of array `s` bound. Inner for loop will give total days for each segment.
3. If the total days matches for the current segment, then increment the count.
4. Repeat for every element and return count.
Have you got better solution or found this useful ? Let us know in the comments. Thanks for reading.