我将以下code尽可能地从Java翻译成C#:
public double maxProfit(double[] prices, int K)
{
if (K == 0 || prices.Length == 0)
{
return 0;
}
var dp = new double[K + 1, prices.Length];
for (int i = 1; i < K + 1; i++)
{
double maxDiff = -prices[0];
for (int j = 1; j < prices.Length; j++)
{
dp[i, j] = Math.Max(dp[i, j - 1], prices[j] + maxDiff);
maxDiff = Math.Max(maxDiff, dp[i - 1, j] - prices[j]);
}
}
printTrans(dp, prices, K);
return dp[K, prices.Length - 1];
}
public void printTrans(double[,] dp, double[] prices, int K)
{
int i = K - 1;
int j = prices.Length;
var priceList = new List<double>();
while (true)
{
if (i == 0 || j == 0)
{
break;
}
if (dp[i, j] == dp[i, j - 1])
{
j = j - 1;
}
else
{
priceList.Add(j);
double maxDiff = dp[i, j] - prices[j];
for (int z = j - 1; z >= 0; z--)
{
if (dp[i - 1, z] - prices[z] == maxDiff)
{
i = i - 1;
j = z;
priceList.Add(j);
break;
}
}
}
}
while (priceList.Count > 0)
{
Console.WriteLine("Buy @ " + prices[priceList.IndexOf(0)]);
Console.WriteLine("Sell @ " + prices[priceList.IndexOf(0)]);
}
}
第二行方法出现错误:
if (dp[i, j] == dp[i, j - 1])
和
for (int z = j - 1; z >= 0; z--)
{
if (dp[i - 1, z] - prices[z] == maxDiff)
我得到Index was outside the bounds of the array
。错误。我理解这个错误意味着什么,但我不知道我要解决它。我花了很多时间来理解这段代码的第一部分,但对于第二部分,我感到很茫然。
还有什么是Java pollFirst()
方法的C#等价物?
答案 0 :(得分:1)
可能这一行是原因
public void printTrans(double[,] dp, double[] prices, int K)
{
int i = K - 1;
int j = prices.Length; // <=== this line is the cause
导致j
引用超出2D数组范围的索引。
如果您已从java
移植,请重新检查您的java代码。
要么划线
int j = prices.Length - 1;
或者您需要更改创建阵列的方式
var dp = new double[K + 1, prices.Length]; // <-- prices.Length would have to change here