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 3.19

    先求模拟信号经过采样后,对应的数字角频率: 明显看出,第3种采样出现假频了.DTFT是以2π为周期的,所以假频出现在10π-2kπ=0处. 代码: %% ----------------------- ...

  2. hdu1428 记忆化搜索(BFS预处理最短路径和+DP+DFS)

    题意:有一块 n * n 大小的方形区域,要从左上角 (1,1)走到右下角(n,n),每个格子都有通过所需的时间,并且每次所走的下一格到终点的最短时间必须比当前格子走到重点的最短时间短,问一共有多少种 ...

  3. solrcloud配置中文分词器ik

    无论是solr还是luncene,都对中文分词不太好,所以我们一般索引中文的话需要使用ik中文分词器. 三台机器(192.168.1.236,192.168.1.237,192.168.1.238)已 ...

  4. sqlserver linux 容器运行

    sqlserver linux 版本的容器大小目前已经相对比较小了,对于开发来说已经比较方便了 docker-compose 文件 version: "3" services: d ...

  5. TensorFlow笔记-07-神经网络优化-学习率,滑动平均

    TensorFlow笔记-07-神经网络优化-学习率,滑动平均 学习率 学习率 learning_rate: 表示了每次参数更新的幅度大小.学习率过大,会导致待优化的参数在最小值附近波动,不收敛:学习 ...

  6. 开发vue全局插件的4种方式

    定义全局插件的步骤 定义全局插件 pluginsUtil.js Vue.js 的插件应当有一个公开方法 install .这个方法的第一个参数是 Vue 构造器,第二个参数是一个可选的选项对象: ex ...

  7. 如何调试触发器-MSSQL (转帖)

    调试触发器 //------------------------------------- 作者:四海为圈(原创) //------------------------------------- 1. ...

  8. 51nod 1673 树有几多愁——虚树+状压DP

    题目:http://www.51nod.com/Challenge/Problem.html#!#problemId=1673 建一个虚树. 一种贪心的想法是把较小的值填到叶子上,这样一个小值限制到的 ...

  9. Flyway 简单入门教程

    原文地址:Flyway 简单入门教程 博客地址:http://www.extlight.com 一.前言 Flyway 是一款开源的数据库版本管理工具,它更倾向于规约优于配置的方式.Flyway 可以 ...

  10. RFID:ISO14443、15693、18000体系分析

    射频标签的通信标准是标签芯片设计的依据,目前国际上与RFID相关的通信标准主要有:ISO/IEC 18000标准(包括7个部分,涉及125KHz, 13.56MHz, 433MHz, 860-960M ...