This repository has been archived by the owner on Aug 23, 2023. It is now read-only.
/
MaxProfitKTransactions.cs
76 lines (64 loc) · 2.25 KB
/
MaxProfitKTransactions.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CS.Problems.DynamicProgramming.Maximizing
{
/// <summary>
/// Problem details below
/// http://www.geeksforgeeks.org/maximum-profit-by-buying-and-selling-a-share-at-most-k-times/
/// </summary>
public class MaxProfitKTransactions
{
public static int GetProfit(int[] sharePrices, int k)
{
return GetProfit(sharePrices, k, sharePrices.Length - 1,
new Dictionary<string, int>());
}
/// <summary>
/// DP top down
/// </summary>
/// <param name="sharePrices"></param>
/// <param name="k"></param>
/// <param name="day"></param>
/// <param name="netBestProfit"></param>
/// <returns></returns>
private static int GetProfit(int[] sharePrices,
int k, int day,
Dictionary<string, int> cache)
{
var cacheKey = $"{k}-{day}";
if(cache.ContainsKey(cacheKey))
{
return cache[cacheKey];
}
//cannot make profit on day 0
//or when we can't make any more transactions
if (day == 0 || k == 0)
{
return 0;
}
var bestProfit = 0;
for (int prevDay = 0; prevDay < day; prevDay++)
{
//profit when we buy previous day and
//sell current day share
var pickProfit = 0;
//only makes sense to buy & sell if prev share
//is less than current
if (sharePrices[prevDay] < sharePrices[day])
{
pickProfit = GetProfit(sharePrices, k - 1, prevDay, cache)
+ (sharePrices[day] - sharePrices[prevDay]);
}
//see the result when we don't buy & sell this pair
var skipProfit = GetProfit(sharePrices, k, prevDay, cache);
//update local max
bestProfit = Math.Max(bestProfit, Math.Max(pickProfit, skipProfit));
}
cache.Add(cacheKey, bestProfit);
return bestProfit;
}
}
}