We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Subarray Division
Subarray Division
+ 0 comments My code in c language
#include<stdio.h> int main(){ int n,d,m,i,c=0,sum=0,j; printf("Please inter number of bars in chocolate: "); scanf("%d",&n); int a[n]; printf("Input numbers on each of the squares of chocolate\n"); for(i=0; i<n; i++){ scanf("%d", &a[i]); } printf("Ron's birth day and month :"); scanf("%d %d", &d,&m); for(i=0; i<n; i++){ for(j=i; j<(i+m); j++){ sum=sum+a[j]; } if(sum==d){ c++; } sum=0; } printf("%d",c); }
+ 0 comments "C++ Solution"
#include <iostream> using namespace std; int main(){ int size; cin >> size; int ar[size]; for (int i = 0; i < size; i++){ cin >> ar[i]; } int d, m; cin >> d >> m; int sum = 0; int count = 0; for (int i = 0; i < size; i++){ for (int j = i; j < m + i; j++){ sum += ar[j]; } if (sum == d){ count++; } sum = 0; } cout << count; }
+ 0 comments "Java Solution"
public static int birthday(List<Integer> s, int d, int m) { // Write your code here int count=0; for(int i=0;i<s.size()-(m-1);i++) { int sum=0; for(int j=i;j<m+i;j++) { sum +=s.get(j); } if(sum==d) { count++; } } return count; }
+ 1 comment A well optimized Javascript solution uses a sliding window technique. O(n) in time complexity where n is the length of the array.
function birthday(s, d, m) { let start = 0; let end = m; let subarray = []; let noOfSegments = 0; // If the array is empty or no of squares < m first criteria becomes false // return 0; if(!s.length || s.length < m){ return 0; } // If no of squares == `m` check whether the sum of the squares == d // If so return 1 else 0 if(s.length === m) { if(s.reduce((sum, currentValue) => sum + currentValue) === d){ return 1; } return 0; } // Checking each and every subarray combinations using sliding window technique // If mentioned criteria meets add 1 to the noOfSegment while(end <= s.length) { subarray = []; for(let i = start; i < end; i++) { subarray.push(s[i]); } if(subarray.reduce((sum, currentValue) => sum + currentValue) === d) { noOfSegments++; } start++; end++ } return noOfSegments; }
+ 0 comments **Javascript Solution: **
function birthday(s, d, m) { let total = 0; if(s.length == 1 && s[0] == d) return 1; for(let i =0; i < s.length -1; i++) { if(s.slice(i,i+m).reduce((a,b) => a+b) == d) total++; } return total; }
Load more conversations
Sort 2624 Discussions, By:
Please Login in order to post a comment