STOCK MARKET

Stock Market

If you have to make money, go to the stock market and if you have to lose money then also go to the stock market. Tina recently read this line and she wants to make money so she goes to the stock market. In the stock market, you buy and sell a stock. Now, she is given a list of price predictions of stock for next few days and since she is a computer programmer she wants to use her coding skills to find out what could be the maximum profit she could make out of given stock prices. There are a few rules she has to follow :

  • A new transaction can only start after the previous transaction is complete. i.e. we can only hold at-most one share at a time.
  • We are allowed to make unlimited stock transactions.

Input format

First line contains an integer T, number of test cases. Then follows T test cases. Each test case consists of two lines. First line contains N. Second lines contain N space separated integers.

Output format

Print T lines, each containing maximum profit that can be gained.

Constraints

1<=T<=10
1<=n<2∗10^6
1<=A[i]<10^7

Example

Input

2
8
1 2 5 8 7 6 9 5
5
1 2 3 4 5

Output

10
4

i did it in this way its working for basic test cases can anyone let me know which case i’m missing

#include <bits/stdc++.h>
using namespace std;

int main()
{
//write your code here
int t;
cin>>t;
while(t–){
int n;
cin>>n;
if(n<1){
cout<<“0”<<endl;
}
else{
vector v;
for(int i=0;i<n;i++){
int x;
cin>>x;
v.push_back(x);
}
stack st;
int sum=0;
for(int i=0;i<v.size();i++){
if(st.empty()|| st.top()<=v[i]){
st.push(v[i]);
}
else{
int top1=st.top();
int top2;
while(!st.empty()){
top2=st.top();
st.pop();
}
st.push(v[i]);
sum+=(top1-top2);
}
}

if(st.size()>1){
  int top1=st.top();
    int top2;
    while(!st.empty()){
        top2=st.top();
      st.pop();
    }
    // cout<<top1<<" "<<top2<<endl;
    sum+=(top1-top2);
}
cout<<sum<<endl;

}
}
return 0;
}

find out local minima and local maxima and buy at minima and sell at maxima and sum the profit that will be your answer btw use code formatting this code is unreadable like that