Given an Array A consisting of 0's and 1's of length N., The goodness of a subarray is defined as difference between number of 1's and number of 0's present in the subarray.Output the length of longest subarray with maximum value of goodness.
Example:
Input: n = 14, a = {1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0}
Output: 8
Approach
C++
#include <bits/stdc++.h>using namespace std;int maximumGoodness(int n, int a[]){int ans = 0, max1 = 0, sum = 0, cnt = 0;for (int i = 0; i < n; i++){int x;if (a[i] == 0)x = -1;elsex = 1;sum += x;cnt++;if (sum >= max1){max1 = sum;if (cnt > ans)ans = cnt;}if (sum < 0){sum = 0;cnt = 0;}}return ans;}int main(){int n = 14;int a[n] = {1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0};cout << maximumGoodness(n, a) << "\n";return 0;}
Read Interview Questions
Exception Handling Interview Questions
DBMS Interview Questions Set -1
DBMS Interview Questions Set -2
JPA Interview Questions Set -1
Spring Boot Interview Questions Set 1
Spring Boot Interview Questions Set 2
No comments:
Post a Comment