Task: The price of stock in every day given in an array of size N, Find which day to buy and sell on stock to get the maximum profit.
Example:
Input:
2
5
100 180 260 310 40
3
100 50 30
Output:
(0 3)
No Profit // If no profit print "No Profit".
Here is the Code:
Program in C++:
- #include<iostream>
- using namespace std;
- void stockBuyAndSell(int *a,int n)
- {
- int c=0;
- for(int i=1;i<n;i++)
- {
- if(a[i-1]<a[i])
- {
- cout<<"("<<i-1<<" ";
- i++;
- while(i<n)
- {
- if(a[i-1]<a[i])
- {
- i++;
- }
- else break;
- }
- cout<<i-1<<")"<<" ";
- c++;
- }
- }
- if(c==0) cout<<"No Profit";
- }
- int main()
- {
- int t;
- cin>>t;
- while(t--)
- {
- int n;
- cin>>n;
- int a[n];
- for(int i=0;i<n;i++)
- {
- cin>>a[i];
- }
- stockBuyAndSell(a,n);
- cout<<endl;
- }
- return 0;
- }
Here is the Video:
Comments
Post a Comment