解题思路
题目中特别强调了同一天不能既卖出又买入,实际上则是一个语义陷阱,乍一看是这么回事,实际上在计算中不用特别处理。
1.本体要求尽可能多的完成交易,首选贪心算法取当前最优解,即如果第二天的价格比第一天高我们就买入卖出,不考虑间隔的问题。
2.假设连续三天价格为A B C,且A<B<C,那么A买入C卖出和A买入B卖出B再买入C再卖出,数学结果是一样的。
3.假设连续四天价格为A B C D,A<B B>C C<D,依然不会发生错误。
C#代码
public static int[] nums1 = new int[6] { 7, 1, 5, 3, 6, 4 };
public static int[] nums2 = new int[5] { 1, 2, 3, 4, 5 };
public static int maxProfit(int[] nums)
{
if (nums.Length < 2) return 0;
int maxProfit = 0;
for (int i = 1; i < nums.Length; i++)
{
if (nums[i] - nums[i - 1] > 0)
{
maxProfit += nums[i] - nums[i - 1];
}
}
return maxProfit;
}