Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Create: 0123-best-time-to-buy-and-sell-stock-iii.cpp#4872

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Open
singhsayan wants to merge1 commit intoneetcode-gh:main
base:main
Choose a base branch
Loading
fromsinghsayan:add-0123-best-time-stock-iii
Open
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletionscpp/0123-best-time-to-buy-and-sell-stock-iii.cpp
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
class Solution {
public:
int maxProfitFromDay(int day, int canBuy, int transactionsRemaining,
vector<int>& prices,
vector<vector<vector<int>>>& dp) {
int n = prices.size();

// Base cases
if (day == n || transactionsRemaining == 0) return 0;

// Return already computed state
if (dp[day][canBuy][transactionsRemaining] != -1) {
return dp[day][canBuy][transactionsRemaining];
}

int profit = 0;
if (canBuy) {
// Option 1: Buy the stock today
int buyToday = -prices[day] + maxProfitFromDay(day + 1, 0, transactionsRemaining, prices, dp);
// Option 2: Skip buying today
int skipToday = maxProfitFromDay(day + 1, 1, transactionsRemaining, prices, dp);
profit = max(buyToday, skipToday);
} else {
// Option 1: Sell the stock today
int sellToday = prices[day] + maxProfitFromDay(day + 1, 1, transactionsRemaining - 1, prices, dp);
// Option 2: Skip selling today
int skipToday = maxProfitFromDay(day + 1, 0, transactionsRemaining, prices, dp);
profit = max(sellToday, skipToday);
}

return dp[day][canBuy][transactionsRemaining] = profit;
}

int maxProfit(vector<int>& prices) {
int n = prices.size();
// 3D DP: dp[day][canBuy][transactionsRemaining]
vector<vector<vector<int>>> dp(n, vector<vector<int>>(2, vector<int>(3, -1)));

// Start at day 0, with option to buy, and 2 transactions allowed
return maxProfitFromDay(0, 1, 2, prices, dp);
}
};


[8]ページ先頭

©2009-2025 Movatter.jp