o1-mini-2024-09-12· OpenAI
WildChat-4.8M (AI2)
// A Simple C++ program to find longest common // subarray of two binary arrays with…
- User
// A Simple C++ program to find longest common // subarray of two binary arrays with same sum #include<bits/stdc++.h> using namespace std;
// Returns length of the longest common subarray // with same sum int longestCommonSum(vector& a, vector& b) {
int res = 0; // One by one pick all possible starting points // of subarrays int n = a.size(); for (int i = 0; i < n; i++) { // Initialize sums of current subarrays int sum1 = 0, sum2 = 0; // Consider all ending points starting with a[i] for (int j = i; j < n; j++) { sum1 += a[j]; sum2 += b[j]; // If sums are the same and current length // is more than res, update res if (sum1 == sum2) { res = max(res, j - i + 1); } } } return res;}
int main() { vector a = {0, 1, 0, 1, 1, 1, 1}; vector b = {1, 1, 1, 1, 1, 0, 1};
cout << longestCommonSum(a, b); return 0; }Give me code in JavaScript
without changing variable name and also do not change comments
have one line space before every comment.
don’t use class if needed then name it GfG
don’t use public if not needed.
- Assistant
// A Simple C++ program to find longest common // subarray of two binary arrays with same sum function longestCommonSum(a, b) { let res = 0; // One by one pick all possible starting points // of subarrays let n = a.length; for (let i = 0; i < n; i++) { // Initialize sums of current subarrays let sum1 = 0, sum2 = 0; // Consider all ending points starting with a[i] for (let j = i; j < n; j++) { sum1 += a[j]; sum2 += b[j]; // If sums are the same and current length // is more than res, update res if (sum1 === sum2) { res = Math.max(res, j - i + 1); } } } return res; } let a = [0, 1, 0, 1, 1, 1, 1]; let b = [1, 1, 1, 1, 1, 0, 1]; console.log(longestCommonSum(a, b));