-
Notifications
You must be signed in to change notification settings - Fork 1
/
123.BestTimetoBuyandSellStockIII.cs
37 lines (32 loc) · 1.12 KB
/
123.BestTimetoBuyandSellStockIII.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
using System;
public class Solution {
public int MaxProfit(int[] prices) {
int[] leftProfit = new int[prices.Length];
int[] rightProfit = new int[prices.Length];
// iterate from left to right
var minPrice = int.MaxValue;
var leftMaxProfit = 0;
for (var i = 0; i < prices.Length; ++i)
{
minPrice = Math.Min(minPrice, prices[i]);
leftMaxProfit = Math.Max(leftMaxProfit, prices[i] - minPrice);
leftProfit[i] = leftMaxProfit;
}
// iterate from right to left
var maxPrice = int.MinValue;
var rightMaxProfit = 0;
for (var i = prices.Length - 1; i >= 0; --i)
{
maxPrice = Math.Max(maxPrice, prices[i]);
rightMaxProfit = Math.Max(rightMaxProfit, maxPrice - prices[i]);
rightProfit[i] = rightMaxProfit;
}
// merge two profits
var maxProfit = 0;
for (var i = 0; i < prices.Length; ++i)
{
maxProfit = Math.Max(maxProfit, leftProfit[i] + rightProfit[i]);
}
return maxProfit;
}
}