All suggestions are welcome. Please upvote if you like it. Thank you.
Leetcode Problem Link: 121. Best Time to Buy and Sell Stock
Brute Force Solution:
class Solution {
public:
int maxProfit(vector<int>& prices) {
// Brute Force Solution Time O(N^2) & Auxiliary Space O(1)
int len=prices.size(),profit=0;
for(int i=0;i<len;i++){
for(int j=i+1;j<len;j++){
if(prices[j]>prices[i]){
int pro=prices[j]-prices[i];
profit=max(profit,pro);
}
}
}
return profit;
}
};
Efficient Solution:
class Solution {
public:
int maxProfit(vector<int>& prices) {
// Efficient Solution Time O(N) & Auxiliary Space O(1)
int min_val=INT_MAX,profit=0,len=prices.size();
for(int i=0;i<len;i++){
min_val=min(min_val,prices[i]);
profit=max(profit,prices[i]-min_val);
}
return profit;
}
};
All suggestions are welcome. Please upvote if you like it. Thank you.
Top comments (0)