Maximum goodness

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 nint a[])
{
    int ans = 0max1 = 0sum = 0cnt = 0;
    for (int i = 0i < ni++)
    {
        int x;
        if (a[i] == 0)
            x = -1;
        else
            x = 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] = {11110011000100};

    cout << maximumGoodness(na<< "\n";

    return 0;
}


Read Interview Questions

Exception Handling Interview Questions

DBMS Interview Questions Set -1

DBMS Interview Questions Set -2

SQL Interview Question Set -1

SQL Interview Question Set -2

JPA Interview Questions Set -1

JPA Interview Question Set -2

Hibernate Interview Questions

Spring Boot Interview Questions Set 1

Spring Boot Interview Questions Set 2


No comments:

Post a Comment