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

Commit ef3c997

Browse files
ADD Best-Time-To-Buy-And-Sell-Stock-With-Cooldown problem #69
1 parent 2f6bb18 commit ef3c997

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
using System;
2+
3+
public class Solution
4+
{
5+
public static int MaxProfit(int[] prices)
6+
{
7+
int soldProfit = 0; // Profit when stock is sold today
8+
int restProfit = 0; // Profit when we do nothing today
9+
int holdProfit = int.MinValue; // Profit when we hold stock today
10+
11+
for (int i = 0; i < prices.Length; i++)
12+
{
13+
int previousSoldProfit = soldProfit; // Store previous day's sold profit
14+
soldProfit = holdProfit + prices[i]; // Update sold profit by selling stock today
15+
holdProfit = Math.Max(holdProfit, restProfit - prices[i]); // Update hold profit
16+
restProfit = Math.Max(restProfit, previousSoldProfit); // Update rest profit
17+
}
18+
19+
return Math.Max(soldProfit, restProfit); // Return the maximum profit possible
20+
}
21+
22+
public static void Main(string[] args)
23+
{
24+
int[] prices = { 1, 2, 3, 0, 2 };
25+
26+
Console.WriteLine(MaxProfit(prices));
27+
28+
Console.ReadKey();
29+
}
30+
}
31+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /