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. set 与 map 的第一次尝试

    map 杭电6015http://acm.hdu.edu.cn/showproblem.php?pid=6015 基本用法:map<string,int>mp;   mp[class[ i ...

  2. BC32(hdu5182~5185)

    恩……又是一个悲伤的故事,然后BC做出来一题,因为自己傻逼,可能紧张,也可能是其他,反正没看全题目就敲,敲完WA,WA完改,改完WA,没了……大概五十几分钟WA了五法,然后问了才知道没看全,就这样,后 ...

  3. day35 python学习GIL解释器锁

    二 GIL介绍 GIL本质就是一把互斥锁,既然是互斥锁,所有互斥锁的本质都一样,都是将并发运行变成串行,以此来控制同一时间内共享数据只能被一个任务所修改,进而保证数据安全. 可以肯定的一点是:保护不同 ...

  4. hasura graphql-engine v1.0.0-alpha25 的几个方便功能

    hasura graphql-engine 是一个很不错的graphql 引擎,但是我们的数据模型经常可能会有变动, 但是以前的版本对于这些的处理,官方的方式是删除元数据,重启server,都不是很好 ...

  5. log4net保存到数据库系列五、新增数据库字段

    园子里面有很多关于log4net保存到数据库的帖子,但是要动手操作还是比较不易,从头开始学习log4net数据库日志一.WebConfig中配置log4net 一.WebConfig中配置log4ne ...

  6. Centos 6.5 yum 安装Apache软件

    首先在系统上面查询一下是否已经安装了apache 软件[Apache软件在linux系统里的名字是httpd] rpm    -qa    httpd 如果有返回的信息,则会显示已经安装的软件.如果没 ...

  7. MySQL5.5.19安装

    本文详细介绍了Windows下安装MySQL5.5.19的全过程,希望对初学者有帮助.  http://dl.pconline.com.cn/html_2/1/79/id=465&pn=0.h ...

  8. js操作cookie(转载:经测试可用)

    /***js操作cookie,star***/ function addCookie(objName,objValue,objsec){//添加cookie  var str = objName + ...

  9. springMVC参数绑定JSON类型的数据

    需求就是: 现在保存一个Student,并且保存Student的friend,一个student会有多个朋友,这里要传递到后台的参数是: var friends = new Array(); var ...

  10. java web 程序---缓冲代码

    在写验证码的时候,我的验证码是随机的,所以每次点击时,刷新页面,验证码都会改变. 可是,当我点击刷新时,验证码不变,说明,没有缓冲. 这里差三行代码. response.setHeader(" ...