博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Best Time to Buy and Sell Stock II
阅读量:4551 次
发布时间:2019-06-08

本文共 1416 字,大约阅读时间需要 4 分钟。

This problem is similar to . Given prices, we find the day (denoted as buy) of the first local minimum and the day (denoted as sell) of the first local maximum (note that we initialize sell to be buy + 1 each time to guarantee the transaction is valid). Then we earn the profit prices[sell] - prices[buy], after which we update buy to besell + 1 to check for the remaining prices.

The code is as follows.

1 class Solution { 2 public: 3     int maxProfit(vector
& prices) { 4 int buy = 0, sell = 0, profit = 0, n = prices.size(); 5 while (buy < n && sell < n) { 6 while (buy + 1 < n && prices[buy + 1] < prices[buy]) 7 buy++; 8 sell = buy; 9 while (sell + 1 < n && prices[sell + 1] > prices[sell])10 sell++;11 profit += prices[sell] - prices[buy];12 buy = sell + 1;13 }14 return profit;15 }16 };

 shares a super-concise code, which is rewritten below.

1 class Solution {2 public:3     int maxProfit(vector
&prices) {4 int res = 0;5 for (int p = 1; p < (int)prices.size(); ++p) 6 res += max(prices[p] - prices[p - 1], 0); 7 return res;8 }9 };

The above code cleverly takes advantage of the cancelling of neighboring elements in prices to give the correct result.

转载于:https://www.cnblogs.com/jcliBlogger/p/4548108.html

你可能感兴趣的文章
Android自定义控件(五)自定义Dialog QuickOptionDialog
查看>>
初学java之面板布局的控制
查看>>
简单的验证码识别(opecv)
查看>>
一款基于jQuery的图片分组切换焦点图插件
查看>>
Python学习-字符串函数操作3
查看>>
MySQL存储二进制数据
查看>>
万网博通NMSS平台二次开发(UDP方式传输)
查看>>
Python爬虫入门 1 Python环境的安装
查看>>
iOS中GCD的使用小结
查看>>
HTML 之 Web页面表单form中只有一个input的text元素,按回车默认提交
查看>>
[BZOJ2870]最长道路tree
查看>>
存储过程简单的动态订单号
查看>>
关于从jsp 中 引用 js 中的里层function
查看>>
读取当前配置文件的方法
查看>>
asp.net 页面之间传值的几种方式
查看>>
.net带事件的对象BinaryFormatter 序列化失败
查看>>
PL/SQL之游标的使用
查看>>
【java初探外篇01】——关于Java修饰符
查看>>
23种设计模式入门之学习目录
查看>>
58. Length of Last Word
查看>>