forked from sudheerkumar67/HacktoberFEST-2023
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create best_time_to_buy_sell_stock.cpp
- Loading branch information
1 parent
8f6073b
commit 85902e6
Showing
1 changed file
with
29 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |