Stock buy and sell | Practice | GeeksforGeeks

The cost of stock on each day is given in an array A[] of size N. Find all the days on which you buy and sell the stock so that in between those days your profit is maximum.
Note: There may be multiple possible solutions. Return any one of them. Any correct solution will result in an output of 1, whereas wrong solutions will result in an output of 0.

Example 1:
Input:
N = 7
A[] = {100,180,260,310,40,535,695}
Output:
1
Explanation:
One possible solution is (0 3) (4 6)
We can buy stock on day 0,
and sell it on 3rd day, which will 
give us maximum profit. Now, we buy 
stock on day 4 and sell it on day 6.

Example 2:
Input:
N = 5
A[] = {4,2,2,2,4}
Output:
1
Explanation:
There are multiple possible solutions.
one of them is (3 4)
We can buy stock on day 3,
and sell it on 4th day, which will 
give us maximum profit.

Your Task:
The task is to complete the function stockBuySell() which takes an array A[] and N as input parameters and finds the days of buying and selling stock. The function must return a 2D list of integers containing all the buy-sell pairs. If there is No Profit, return an empty list. 
 
Note: Since there can be multiple solutions, the driver code will return 1 if your answer is correct, otherwise, it will return 0. In case there's no profit the driver code will return the string "No Profit" for a correct solution.

Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)

Constraints:
2 ≤ N ≤ 106
0 ≤ A[i] ≤ 106
0
sangrambachu1 day ago
		let profit = [];
        
        for(let i=1; i<n; i++) {
            if(A[i] > A[i-1]) {
                profit.push([i-1, i]);
            }
        }
        
        return profit;
0
avfriendscc1 day ago
just whenever the curr price is higher than the previous day price it means we can buy the share yesterday and sold it today. This is also a valid pair [prev_day, curr_day] if (curr_day>prev_day)
 
//c++
vector<vector<int> > stockBuySell(vector<int> A, int n){       vector<vector<int>> a;              for(int i=1; i<n; i++){           if(A[i]>A[i-1]){               vector<int>t;               t.push_back(i-1);               t.push_back(i);               a.push_back(t);           }       }              return a;          }
0
aroopghosh5531 day ago
vector<vector<int> > stockBuySell(vector<int> a, int n){
        int curr = 0;
        vector<vector<int>> ans;
        for(int i = 1; i < n; i++){
            if(a[i] <= a[i - 1]){
                vector<int> temp;
                if(a[i - 1] - a[curr] > 0){
                    temp.push_back(curr);
                    temp.push_back(i - 1);
                    ans.push_back(temp);;
                }
                curr = i;
            }
            if(i == n - 1 && a[curr] < a[i]){
                vector<int> temp;
                temp.push_back(curr);
                temp.push_back(i);
                ans.push_back(temp);
            }
        }
        return ans;
    }
+1
lawbindpandey01w1 week ago
The approach is to find the bottom points and peak points.
i.e when the price are falling let them fall and once it reaches
bottom i.e A[i] > A[i-1] then A[i - 1] is bottom point note it as start i.e start = A[i - 1] and when the price goes up let it rise and when the price reaches peak i.e A[j] < A[j - 1] then A[j - 1] is peak now mark it as end i.e end = A[j - 1] the max profit you'll get is when you'll buy stock at start and sell it on end and now find all such possible intervals from given array A
 
 
vector<vector<int> > stockBuySell(vector<int> A, int n){       // code here                     vector<vector<int>> v;              int st = 0, end = 0;              for(int i = 1; i < n; i++){                                 if(A[i] > A[i - 1]) end++;                      else{                              if(end > st){                   vector<int> v1(2);                   v1[0] = st, v1[1] = end;                   v.push_back(v1);               }                              bool flag = 0;               while(i < n && A[i] <= A[i - 1]){                   i++;                   flag = 1;               }               if(flag){                   i--;                   st = i;                   end= i;               }                          }                  }              if(end > st){           vector<int> v1(2);           v1[0] = st; v1[1] = end;           v.push_back(v1);       }              /*(for(auto x : v){           for(auto x1 : x) cout << x1 << " ";           cout << "\n";       }*/              return v;          }
+1
shivi13verma1 week ago
easy approch 
profit=[] for i in range(1,n):     if A[i]>A[i-1]:         profit.append([i-1,i])       return profit
-1
sreenivasulushreeharish1 week ago
DUMMY CPP SOLUTIONS
 
class Solution{public:   //Function to find the days of buying and selling stock for max profit.   vector<vector<int> > stockBuySell(vector<int> A, int n){       // code here              vector<vector<int>> rV;              vector<int> dummy;              bool incr = false;              for(int i = 0; i < n-1; i++){           if(A[i] < A[i+1] && !incr){               dummy.push_back(i);               incr = !incr;           }                      else if(A[i] > A[i+1] && incr){               incr = !incr;               dummy.push_back(i);               rV.push_back(dummy);               dummy.clear();           }       }              if(dummy.size() == 1){           dummy.push_back(n-1);           rV.push_back(dummy);       }              return rV;   }};
+1
unknownsingh2 weeks ago
EASY!!!
C++ Solution.
 
 
vector<vector<int> > stockBuySell(vector<int> arr, int n)   {       vector<vector<int>>v;       int x=0;       for(int i=0; i+1<n; i++)       {           if(arr[i]>arr[i+1])           {               if(x!=i)                   v.push_back({x, i});               x=i+1;           }       }       if(x!=n-1 && arr[x]<arr[n-1])           v.push_back({x, n-1});       return v;   }
+1
kaleem5302 weeks ago
Question description is not clear 
update it with leetcode buy and sell stock stock
0
mahesh_phutane2 weeks ago
#Simple java solution --> 0.86 sec

class Solution{
    //Function to find the days of buying and selling stock for max profit.
    ArrayList<ArrayList<Integer> > stockBuySell(int A[], int n) {
        ArrayList<Integer> k;
        ArrayList<ArrayList<Integer> > f = new ArrayList<ArrayList<Integer> >();
        int i = 1;
        while(i<n){
           int flag = 1;
           int idx = i;
            k = new ArrayList<>();
            if(A[i]>A[i-1]){
                idx = i-1;
                flag = 0;
                while(i<n && A[i]>A[i-1]){
                    i+=1;
                }
            }
            if(flag==0){
                k.add(idx);
                k.add(i-1);
                f.add(k);
            }
            if(flag==1){
            i++;
            }
        }
        return f;
    }
}
0
joyrockok2 weeks ago
class Solution{   ArrayList<ArrayList<Integer>> result;ArrayList<Integer> subResult;ArrayList<ArrayList<Integer>> finalResult;   //Function to find the days of buying and selling stock for max profit.   ArrayList<ArrayList<Integer> > stockBuySell(int A[], int n) {       // code here    finalResult = new ArrayList<ArrayList<Integer>>();        int p1=0, p2=1;    long Max = Integer.MIN_VALUE;        while (p1 < n && p2 < n) {          if((A[p2] - A[p1] > Max && A[p2] - A[p1] > 0) && p1 < p2) {      result = new ArrayList<ArrayList<Integer>>();      subResult = new ArrayList<Integer>();            subResult.add(p1);      subResult.add(p2);      result.add(subResult);            Max = A[p2] - A[p1];      p2++;     } else if ((A[p2] - A[p1] < Max || A[p2] - A[p1] <= 0) && p1 < p2) {      if(result != null && result.size() > 0) {       finalResult.add(result.get(0));       result.clear();      }            p1=p2;      Max = Integer.MIN_VALUE;     } else if (A[p2] - A[p1] == Max && p1 < p2) {      p2++;     }             if(p1 == p2) {        p2++;       }    }        if(result != null && result.size()>0) {     finalResult.add(result.get(0));     result.clear();    }        return finalResult;   }}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.