-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem121.cs
47 lines (41 loc) · 1.05 KB
/
Problem121.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
namespace Problems;
public sealed class Problem121
{
// https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/
public int MaxProfit(int[] prices)
{
var (possible, output) = Lazy(prices);
if (possible)
return output;
var l = 0;
var r = 1;
var max = 0;
while (true)
{
if (r == prices.Length)
break;
if (prices[l] < prices[r])
{
var profit = prices[r] - prices[l];
if (profit > max)
max = profit;
r++;
}
else if (prices[l] >= prices[r])
{
l = r;
r++;
}
}
return max;
}
private static (bool possible, int output) Lazy(int[] prices)
{
return prices.Length switch
{
1 => (true, 0),
2 => prices[1] > prices[0] ? (true, prices[1] - prices[0]) : (false, -1),
_ => (false, -1)
};
}
}