In this Subarray Division 2 HackerRank Problem, Two children, Lily and Ron, want to share a chocolate bar. Each of the squares has an integer on it.
Lily decides to share a contiguous segment of the bar selected such that:
- The length of the segment matches Ron’s birth month, and,
- The sum of the integers on the squares is equal to his birth day.
Determine how many ways she can divide the chocolate.
Example
Lily wants to find segments summing to Ron’s birth day, with a length equalling his birth month, . In this case, there are two segments meeting her criteria: and .
Function Description
Complete the birthday function in the editor below.
birthday has the following parameter(s):
- int s[n]: the numbers on each of the squares of chocolate
- int d: Ron’s birth day
- int m: Ron’s birth month
Returns
- int: the number of ways the bar can be divided
Input Format
The first line contains an integer , the number of squares in the chocolate bar.
The second line contains space-separated integers , the numbers on the chocolate squares where .
The third line contains two space-separated integers, and , Ron’s birth day and his birth month.
Constraints
- , where ()
Subarray Division 2 HackerRank Problem Solutions
I will Provide solution in Multiple programming languages for you. If you are not able to find the code in required language then please share in comments so that our team can help you.
Problem Solution in JavaScript
function birthday(s, d, m) {
let result = [];
for (let i = 0; i < s.length; i++) {
let segment = s.slice(i, i + m);
if (
segment.reduce((prev, current) => {
return prev + current;
}) === d
) {
result.push(segment);
}
}
return result.length;
}
Problem Solution in Java
public static int birthday(List<Integer> s, int d, int m) {
if(s.size()==1 && m==1 && d==s.get(0)){
return 1;
}
int counter = 0;
for (int i = 0; i < s.size()-m+1; i++) {
int sum = 0;
int j = i;
while (j < m+i) {
sum += s.get(j);
j+=1;
}
if(sum==d){
counter+=1;
}
}
return counter;
}
Problem Solution in Python
def birthday(s, d, m):
count = 0
start = 0
w_sum = 0
for end in range(len(s)):
w_sum += s[end]
if end + 1 >= m:
if w_sum == d:
count += 1
w_sum -= s[start]
start += 1
return count
Subarray Division 2 Problem Solution in PHP
function birthday($s, $d, $m) {
// Write your code here
$result = 0;
foreach($s as $k => $v){
$seg = array_slice($s, $k, $m);
if(array_sum($seg) == $d && count($seg) == $m){
$result++;
}
}
return $result;
}