-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path121-Best-Time-to-Buy-and-Sell-Stock.cs
More file actions
46 lines (42 loc) · 1.05 KB
/
Copy path121-Best-Time-to-Buy-and-Sell-Stock.cs
File metadata and controls
46 lines (42 loc) · 1.05 KB
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
#region Two Pointers
// Time O(n)
// Space O(1)
public class Solution
{
public int MaxProfit(int[] prices)
{
int least = prices[0],
profit = 0;
foreach (int price in prices)
{
least = Math.Min(least, price);
profit = Math.Max(profit, price - least);
}
return profit;
}
}
#endregion
#region Iterate Backwards
// Time O(n)
// Space O(1)
public class Solution
{
public int MaxProfit(int[] prices)
{
// Iterate through array backwards
// At each point, take max of max seen and cur, then subtract cur from max seen and take max of that value and max profit so far
// Return max profit so far at end
int cur,
maxSeen,
maxProfit;
cur = maxSeen = maxProfit = 0;
for (int i = prices.Length - 1; i >= 0; i--)
{
cur = prices[i];
maxSeen = Math.Max(cur, maxSeen);
maxProfit = Math.Max(maxSeen - cur, maxProfit);
}
return maxProfit;
}
}
#endregion