Skip to main content

Stock Buy And Sell

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++:

  1. #include<iostream>
  2. using namespace std;
  3. void stockBuyAndSell(int *a,int n)
  4. {
  5.     int c=0;
  6.     for(int i=1;i<n;i++)
  7.     {
  8.         if(a[i-1]<a[i])
  9.         {
  10.             cout<<"("<<i-1<<" ";
  11.             i++;
  12.             while(i<n)
  13.             {
  14.                 if(a[i-1]<a[i])
  15.                 {
  16.                     i++;
  17.                 }
  18.                 else break;
  19.             }
  20.             cout<<i-1<<")"<<" ";
  21.             c++;
  22.         }
  23.     }
  24.     if(c==0) cout<<"No Profit";
  25. }
  26. int main()
  27.  {
  28. int t;
  29. cin>>t;
  30. while(t--)
  31. {
  32.     int n;
  33.     cin>>n;
  34.     int a[n];
  35.     for(int i=0;i<n;i++)
  36.     {
  37.         cin>>a[i];
  38.     }
  39.     stockBuyAndSell(a,n);
  40.     cout<<endl;
  41. }
  42. return 0;
  43. }

Here is the Video: