https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
请检查性能。
假设您有一个数组,其中第一个元素是第一天给定股票的价格。设计一个算法来寻找最大利润。你可以随心所欲地完成多少笔交易(也就是说,买一股,多次卖出一股)。注:您不能同时从事多个交易(即,您必须在再次购买之前出售该股票)。例1:输入:7,1,5,3,6,4输出:7解释:在第2天买进(价格= 1),在第3天卖出(价格= 5),利润= 5-1 = 4。然后在第4天买进(价格= 3),第5天卖出(价格= 6),利润= 6-3 =3。示例2:输入:1,2,3,4,5输出:4解释:第1天买进(价格= 1),第5天卖出(价格= 5),利润= 5-1 = 4。注意,你不能在第一天买,在第二天买,以后再卖,因为你同时从事多种交易。你必须先卖掉,然后再买。示例3:输入:7,6,4,3,1输出: 0解释:在本例中,没有完成任何事务,即最大利润=0。
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ArrayQuestions
{
/// <summary>
/// https://leetcode.com/explore/featured/card/top-interview-questions-easy/92/array/564/
/// </summary>
[TestClass]
public class BestTimetoBuyandSellStockII
{
[TestMethod]
public void AnswerIs7()
{
int[] prices = {7, 1, 5, 3, 6, 4};
Assert.AreEqual(7, MaxProfit(prices));
}
public int MaxProfit(int[] prices)
{
int max = 0;
for (int i = 0; i < prices.Length-1; i++)
{
if (prices[i] < prices[i + 1])
{
max += prices[i + 1] - prices[i];
}
}
return max;
}
}
}发布于 2019-06-21 18:24:17
您的解决方案是具有时间复杂性O(n)的一次遍历。这是拟议解决方案的一个小变体。
staticCalculateMaximumProfit。public方法中的错误用户输入varprices.Length - 1之间的空格return语句之后)应用于您的代码:
public static int CalculateMaximumProfit(int[] prices)
{
prices = prices ?? throw new ArgumentNullException(nameof(prices));
var max = 0;
for (var i = 0; i < prices.Length - 1; i++)
{
if (prices[i] < prices[i + 1])
{
max += prices[i + 1] - prices[i];
}
}
return max;
}https://codereview.stackexchange.com/questions/222194
复制相似问题