首页 > 解决方案 > 如何找到我的 Codechef 解决方案中的缺陷

问题描述

链接到问题

基本问题是找到一个数组的最大子段,该数组在输入中没有至少一个 k 值。

#include<bits/stdc++.h>

using namespace std ;
             
#define ll long long int

void solve()
{
    
      // here the approach is to check from start and keep checking, it take O(n^2) approach but it 
      // should satisfy at least the sub-task but I am getting that too wrong, i.e only one of the
      // two sub-task is getting AC while other WA.
 
    ll i, j, n, k, ans=0, flag=0 ;
    scanf("%lld %lld", &n, &k) ;
    ll a[n+1] ;
    set <int> s ;
    for(i=0 ;i<n ;i++)
    {
        scanf("%lld", &a[i]) ;
    }
    for(i=0 ;i<n ;i++) // this is to start searching for the longest subsegment from start
    {
        s.insert(a[i]) ; // this to keep the count of no. of flavours occuring
        for(j=i+1 ;j<n ;j++) // to continue checking 
        {
            if(s.size()<k && flag==0) 
            {
                s.insert(a[j]) ;
                if(s.size()==k) // if after adding it becomes that condition the size would be one less 
                {
                    ans=max(ans,j-i) ;
                    flag=1 ;
                }
                else
                    ans=max(ans,j-i+1) ;
            }
            else
            {
                s.clear() ;
                break ;
            }
        }
        flag=0 ;
    }
    printf("%lld\n", ans);
}

int main()
{

    ios_base::sync_with_stdio(false) ;
    cin.tie(NULL) ;
    ll t ;
    scanf("%lld", &t) ;
    while (t--)
    {
        solve() ; // solving no. of test cases
    }
    return 0 ;
}

标签: c++setc++14

解决方案


推荐阅读