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. 《DSP using MATLAB》Problem 4.10

    今天擦完了玻璃,尽管有地方不那么明亮干净,冷风中瑟瑟发抖,年也快临近了. 代码是从网上找的, function [p, np, r, nr] = deconv_m(b, nb, a, na) % Mo ...

  2. LeetCode-Microsoft-Add Two Numbers II

    You are given two non-empty linked lists representing two non-negative integers. The most significan ...

  3. socket套接字和驱动绑定分析

    1. socket()系统调用 socket系统调用是哪个:socket()有3个参数,因此搜索SYSCALL_DEFINE3,然后在检索socket即可. SYSCALL_DEFINE3(socke ...

  4. PHP的extension_dir设置问题

    PHP安装时,extension_dir的路径要设成绝对路径:extension_dir = "D:/Tools/php-7.0.5/ext", 不然如果设成extension_d ...

  5. task optimization之superglue分析

    开启logging (例子F:\wamp\www\git_repos\GitHub\GeneralUtility\superglue-master\examples\src\logging.cpp) ...

  6. spring 使用 maven profile

    先看看 maven 定义 profile 的写法 <!-- profiles --> <profiles> <profile> <activation> ...

  7. 如何用Photoshop画一个发光金币(unity游戏素材教程)

    做好的发光金币预览图: 以下为如何用Photoshop画一个发光金币教程: [1]如上图1-2,新建,名称改为Coin,宽度20像素,高度20像素,分辨率72,背景白色: [2]使用Alt+Shift ...

  8. mySQL 教程 第8章 视图

    创建视图的目的 简单 隐藏数据复杂性 安全 可以对视图授权 数据独立 可以屏蔽表结构变化对用户的影响,比如增加列,更改列名 创建视图 1. 创建单表视图 以下视图显示JAVA班的学生姓名.身份证号和班 ...

  9. 阿里巴巴Java开发手册-集合处理

    1. [强制]关于 hashCode 和 equals 的处理,遵循如下规则:      1) 只要重写 equals ,就必须重写 hashCode .      2) 因为 Set 存储的是不重复 ...

  10. Windows下 YOLOv3配置教程(YOLOv3项VS2013平台迁移的方法)

    https://blog.csdn.net/maweifei/article/details/81150489