import java.util.;
import java.io.;
import java.lang.*;
class Solution
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int t,n,i,max,curr,prev,count,j;
t=sc.nextInt();
j=t;
while(t>0)
{
n=sc.nextInt();
max=count=0;
prev=sc.nextInt();
for(i=0;i<n-1;i++)
{
curr=sc.nextInt();
if(prev>max)
{
max=prev;
if(curr<prev)
count++;
}
prev=curr;
}
if(prev>max)
count++;
System.out.println(String.format(“Case #%d: %d”, (j-t+1), count));
t–;
}
}
}
Solve it by dp.
dp(i,j) i is index, j is last taken alphabet.
Just do what the problem statement says.
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t;
cin >> t;
for (int i = 1; i <= t; ++i)
{
int n;
cin >> n;
vector <int> a(n);
for (int i = 0; i < n; ++i) cin >> a[i];
int m = -1, ans = 0;
for (int i = 0; i < n-1; ++i)
{
if (a[i] > m)
{
m = a[i];
if (a[i] > a[i+1]) ++ans;
}
}
if (a[n-1] > m) ++ans;
cout << "Case #" << i << ": " << ans << '\n';
}
}
No need of DP. From the 1st to second last numbers, just check if the current number is greater than the max number till there and if it’s greater than the next number. And then manually check if the max number till the last number is less than it.
i did the same implementation as you have done and got the sample test case correct as well don’t know why i got WA. still thanks.
My bad. This is for 2nd problem.
Make sure it gives 1 as output for n=1
thanks n=1 and max intial value (should be less than 0)were causing the prblm .
just got accepted.
Try chaning initial value of max to -1 instead of zero. Read contraints carefully next time. Good luck
Can u explain the whole solution? I solved with greedy but not getting the dp approach
You should try initiating max with -1 or INT_MIN. do not put it’s value as 0 .
I was facing the same issue and at last I found that.
Yes , its easy, dp not required.
you should check saperately if there is only one element