Question named " Finquest" from algorithm section

Im not getting correct answer please can you check

int main() {

int t;
cin>>t;
while(t--){
	int n;
	cin>>n;
	int a[n],i;
	for(i=0;i<n;i++)cin>>a[i];

	// finding next greatest element to the right of an element
	// and storing in array c[]
	int c[n];
	c[n-1]=a[n-1];

	for(i=n-2;i>=0;i--){
		// finding greatest element to the right starting
		// from backward

		c[i]=max(c[i+1],a[i+1]);
	}

	// if next greatest element is more that its value in 
	//array a[] ( original array means price on the day I purchased ) 
	//then adding to my ans

	int ans=0;
	for(i=0;i<n;i++){
		if(c[i]>a[i]){
			//adding to my ans selling price minus purchased price
			ans+=c[i]-a[i];
		}
	}

	cout<<ans<<endl;
}
return 0;

}

Hey @talhashamim001
Your logic is incoorect
say
3
1 2 5
Now u create max array whch is
5 5 5
Now u will be adding 5-1 + 5-2 =4+3=7
But answer is simplly 4
we purchase on day 1 and sell on day 3

what should be the ans for 1 2 100 ?

i mean n=3 and elements are 1 2 100

99
… . … . … . . . . .

For 1 2 100 2 44 23
purchase on D1 sell on D3 ,purchases on D4 sell on D5
Ans is 100-1 + 44-2 == 99+42 ==141

please check the example cases given in question

Oh okay I mixed it with some other question (Buy & Sell )
Will look into ur code again

long long ans=0; //long long here to avoid overflow
	c[i]=max(c[i+1],a[i]);//a[i] here

sir it working with c[i] = max( c[i+1], a[i+1] ) also just changing it to long long its done …thank you sir!

1 Like