forked from 7oSkaaa/LeetCode_DailyChallenge_2023
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
72 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
Empty file.
25 changes: 25 additions & 0 deletions
25
...ansaction Fee/22- Best Time to Buy and Sell Stock with Transaction Fee (Ahmed Hossam).cpp
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,25 @@ | ||
// Author: Ahmed Hossam | ||
|
||
class Solution { | ||
public: | ||
int maxProfit(vector<int>& prices, int fee) { | ||
// Get the number of prices in the vector. | ||
int n = prices.size(); | ||
|
||
// Initialize variables for cash (available funds) and hold (stock held). | ||
// Set the initial value of hold to the negative of the first stock price. | ||
int cash = 0, hold = -prices[0]; | ||
|
||
// Iterate through the prices starting from the second price. | ||
for(int i = 1; i < n; i++){ | ||
// Calculate the maximum of either keeping the cash as it is or selling the stock and deducting the fee. | ||
cash = max(cash, hold + prices[i] - fee); | ||
|
||
// Calculate the maximum of either keeping the hold as it is or buying the stock and deducting the cash. | ||
hold = max(hold, cash - prices[i]); | ||
} | ||
|
||
// Return the maximum profit (cash) after all transactions. | ||
return cash; | ||
} | ||
}; |
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