public class Solution {
public int MaxProfit(int[] prices) {
var list = new List<KeyValuePair<int, int>>();
//记录所有的极大值和极小值 if (prices.Length <= )
{
return ;
}
else if (prices.Length == )
{
return prices[] - prices[] > ? prices[] - prices[] : ;
}
else
{
for (int i = ; i < prices.Length - ; i++)
{
var last = prices[i - ];
var cur = prices[i];
var next = prices[i + ];
if ((last < cur && cur >= next) || (last <= cur && cur > next))
{
list.Add(new KeyValuePair<int, int>(i, ));//记录极大值
}
if ((last > cur && cur <= next) || (last >= cur && cur < next))
{
list.Add(new KeyValuePair<int, int>(i, -));//记录极小值
}
} var firstnode = list.FirstOrDefault();
var lastnode = list.LastOrDefault(); if (firstnode.Value == )
{
list.Add(new KeyValuePair<int, int>(, -));//第一个坐标当做极小值
}
else if (firstnode.Value == -)
{
list.Add(new KeyValuePair<int, int>(, ));//第一个坐标当做极大值
}
else
{
if (prices[] < prices[prices.Length - ])
{
list.Add(new KeyValuePair<int, int>(, -));//第一个坐标当做极小值
}
else
{
list.Add(new KeyValuePair<int, int>(, ));//第一个坐标当做极大值
}
} if (lastnode.Value == )
{
list.Add(new KeyValuePair<int, int>(prices.Length - , -));//最后一个坐标当做极小值
}
else if (lastnode.Value == -)
{
list.Add(new KeyValuePair<int, int>(prices.Length - , ));//最后一个坐标当做极大值
}
else
{
if (prices[] < prices[prices.Length - ])
{
list.Add(new KeyValuePair<int, int>(prices.Length - , ));//最后一个坐标当做极大值
}
else
{
list.Add(new KeyValuePair<int, int>(prices.Length - , ));//最后一个坐标当做极大值
}
} list = list.OrderBy(x => x.Key).ToList(); var sum = ; var min = -;
var max = -; int pair = ;
for (int i = ; i < list.Count; i++)
{
if (list[i].Value == -)
{
min = list[i].Key;
pair = ;
}
if (pair == && list[i].Value == )
{
max = list[i].Key;
pair += ; }
if (pair == )
{
sum += prices[max] - prices[min];
pair = ;
}
}
return sum;
}
}
}

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/#/description

上面这种方法比较复杂,还有一种更简单直接的方法

public class Solution {
public int MaxProfit(int[] prices) {
int total = ;
for (int i=; i< prices.Length-; i++) {
if (prices[i+]>prices[i]) total += prices[i+]-prices[i];
} return total;
}
}

只要后面的比前面的多,就进行一次买卖。计算的结果是一样的,但是与题意并不相符。题意要求在同一时间不能既买又卖。也就是要尽量减少交易次数。

所以严格来讲,第二种方法并不是是正确的解答,虽然答案一样。

时隔一年半的时间,在学习了贪婪算法的思想后,重新解此题,明白了上面的思想。只要下一次比上一次的金额高,就进行一次累计,C++程序如下:

int maxProfit(vector<int>& prices) {
int sum = ;
if (prices.size() > )
{
int lastP = prices[];
for (int i = ; i < prices.size(); i++)
{
int p = prices[i];
if (p > lastP)
{
sum += p - lastP;
}
lastP = p;
}
}
return sum;
}

补充一个python的实现:

 class Solution:
def maxProfit(self, prices: List[int]) -> int:
n = len(prices)
sums =
for i in range(,n):
if prices[i] > prices[i-]:
sums += prices[i] - prices[i-]
return sums

leetcode122的更多相关文章

  1. LeetCode122:Best Time to Buy and Sell Stock II

    题目: Say you have an array for which the ith element is the price of a given stock on day i. Design a ...

  2. Leetcode-122 Best Time to Buy and Sell Stock II

    #122  Best Time to Buy and Sell Stock II Say you have an array for which the ith element is the pric ...

  3. [Swift]LeetCode122. 买卖股票的最佳时机 II | Best Time to Buy and Sell Stock II

    Say you have an array for which the ith element is the price of a given stock on day i. Design an al ...

  4. LeetCode122.买卖股票的最佳时机II

    给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格. 设计一个算法来计算你所能获取的最大利润.你可以尽可能地完成更多的交易(多次买卖一支股票). 注意:你不能同时参与多笔交易(你必须在再次 ...

  5. LeetCode--122、167、169、189、217 Array(Easy)

    122. Best Time to Buy and Sell Stock II Say you have an array for which the ith element is the price ...

  6. leetcode122 买卖股票的最佳时机 python

    题目:给定一个数组,它表示了一只股票的价格浮动,第i个元素代表的是股票第i天的价格.设计一个函数,计算出该股票的最大收益,注意,可以多次买入卖出,但下一次买入必须是在本次持有股票卖出之后.比如[1,7 ...

  7. leetcode122 Best Time to Buy and Sell Stock

    题意:有一个数组,第i个数据代表的是第i天股票的价格,每天只能先卖出再买进(可以不卖出也可以不买进),求最大收益. 思路:自己去弄几个数组比划比划就知道了,比如[1,2,5,3,6],第一天买进,第二 ...

  8. LeetCode122——Best Time to Buy and Sell Stock II

    题目: Say you have an array for which the ith element is the price of a given stock on day i. Design a ...

  9. leetcode 买卖股票问题

    leetcode121 Best Time to Buy and Sell Stock 说白了找到最大的两组数之差即可 class Solution { public: int maxProfit(v ...

随机推荐

  1. dfs 与 剪枝

    http://blog.csdn.net/u010700335/article/details/44095171

  2. 《DSP using MATLAB》Problem 4.26

    Y(z)部分分式展开, 零状态响应和零输入响应的部分分式展开,

  3. 强大的Java Json工具类

    转自: https://blog.csdn.net/u014676619/article/details/49624165 import java.io.BufferedReader; import ...

  4. Java调用.Net WebService参数为空解决办法 (远程)调试webservice方法

    同事遇到一个很囧的问题,java调,netwebservice的时候,调用无参数方法成功,调用有参数的方法每次我这边的webservice日志都记录参数为空,而我自己.Net程序调用完全没有问题,后面 ...

  5. RAC5——11gR2以后GI进程的变化

    参考文档: 11gR2 Clusterware and Grid Home - What You Need to Know (Doc ID 1053147.1)诊断 Grid Infrastructu ...

  6. C# ObjectArx AutoCAD二次开发(转帖)

    http://www.cnblogs.com/houlinbo/p/3325898.html 1.开发基本资料准备 用Vs2010进行Autocad 2010开发,首先下载ObjectArx 2010 ...

  7. js的模块化规范

    js的模块化规范常见的有:AMD,CMD,commonJS,UMD,es6 前期在没有模块化的时候,js文件十分庞大,于是就按功能抽离划分为多个js文件. 但是在html页面通过script的方式加载 ...

  8. 【Android】Android版本和API Level对应关系

    API Level Notes Android 4.4 19 KITKAT Platform Highlights Android 4.3 18 JELLY_BEAN_MR2 Platform Hig ...

  9. 导出pb模型之后测试的python代码

    链接:https://blog.csdn.net/thriving_fcl/article/details/75213361 saved_model模块主要用于TensorFlow Serving.T ...

  10. TroubleShoot: Fail to deploy Windows UAP to device: 0x80073CFD

    After creating "Blank App(Windows Universal)" targeting Windows Phone 10 in Visual Studio ...