Skip to content

Commit

Permalink
Create best_time_to_buy_sell_stock.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
srusti610 authored and sudheerkumar67 committed Oct 14, 2023
1 parent 8f6073b commit 85902e6
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions best_time_to_buy_sell_stock.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// C++ code for the above approach
#include <iostream>
using namespace std;

int maxProfit(int prices[], int n)
{
int buy = prices[0], max_profit = 0;
for (int i = 1; i < n; i++) {

// Checking for lower buy value
if (buy > prices[i])
buy = prices[i];

// Checking for higher profit
else if (prices[i] - buy > max_profit)
max_profit = prices[i] - buy;
}
return max_profit;
}

// Driver Code
int main()
{
int prices[] = { 7, 1, 5, 6, 4 };
int n = sizeof(prices) / sizeof(prices[0]);
int max_profit = maxProfit(prices, n);
cout << max_profit << endl;
return 0;
}

0 comments on commit 85902e6

Please sign in to comment.