简体   繁体   中英

What is the time complexity of the following code fragment for Stock Buy & Sell?

Recently I was trying the problem of Stock Buy and Sell in which we can buy a stock on any day and sell it on any upcoming day, and we have to find the maximum profit that we can get.

The solution that first came to my mind was the code below but I'm not able to determine its time complexity. It would be very helpful if you can help with this.

int maxProfit(int price[], int start, int end){
  if(end<=start)
    return 0;

  int profit=0;

  for(int i=start; i<end; i++){

    for(int j=i+1; j<=end; j++){

      if(price[j]>price[i]){

        int curr_profit=price[j]-price[i]+maxProfit(price,start,i-1)+maxProfit(price,j+1,end);
        profit=max(profit,curr_profit);
      }
    }

    return profit;
  }
}

I think it gives you Ω(n!)
if we focus only on maxProfit(price,j+1,end) :
At the beginning, the number of elements is n.
At each iteration we have two loop that call maxProfit(price,j+1,end) by decreasing the number of elements by 1.
We get :
n^2 (the 2 first loop) * (n-1)^2 (the first call) * (n-2)^2 (the second call) * (n-3)^2 * ... * (nn-1)^2
this gives O(n!) .

Because i ignored the maxProfit(price,start,i-1) wich give also an additional complexity, so i thought that it will be better to use Ω(n!) to say that it take at least n!.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM