LeetCode----best-time-to-buy-and-sell-stock
来源:互联网 发布:讲诚信知敬畏发言稿 编辑:程序博客网 时间:2024/06/09 19:36
题目描述
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
------------------------------------------------------------------------------------------------------------
求解思路:
1,先找到第一个较小买入价格,然后找到一个较大卖出价格,记录较大利益;
2,(1)当较大价格后一天的价格不小于上次较小价格时,递归求后半部分的较大利益,最终取最大
(2)否则,将后一天价格修改为较小后再同上递归求解。
代码实现:
简洁解答:语言:C++ 运行时间: <1 ms 占用内存:8552K 状态:答案正确
class
Solution {
public
:
int
maxProfit(vector<
int
> &prices) {
if
(prices.size() <=
1
)
{
return
0
;
}
int
max =
0
;
for
(
int
i =
0
; i < prices.size() -
1
; i++)
{
for
(
int
j = i +
1
; j < prices.size(); j++)
{
int
pro = prices[j] - prices[i];
max = pro > max ? pro : max;
}
}
return
max;
}
};
0 0
- 【LeetCode】Best Time to Buy and Sell Stock & Best Time to Buy and Sell Stock
- [LeetCode] [LeetCode]Best Time to Buy and Sell Stock
- 【LeetCode with Python】 Best Time to Buy and Sell Stock
- [LeetCode]Best Time to Buy and Sell Stock
- [LeetCode]Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock
- LeetCode Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock III
- Leetcode: Best time to buy and sell a stock I
- Leetcode: Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock III
- [Leetcode] Best Time to Buy and Sell Stock
- [Leetcode] Best Time to Buy and Sell Stock II
- [Leetcode] Best Time to Buy and Sell Stock III
- LeetCode : Best Time to Buy and Sell Stock II
- [leetcode] Best Time to Buy and Sell Stock
- leetcode 16: Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock
- Android Framework框架之IBinder进程间通信
- NKOI 3805 距离
- 关于sql查询字符char类型数据的条件使用
- 以太坊帮助地址
- ubuntu 挂载 网件路由器 存储设备
- LeetCode----best-time-to-buy-and-sell-stock
- php语法杂记
- HihoCoder 1255(2015 Asia Beijing Regional Contest)
- 数据连接:JDBC+MySql
- Item11 Prefer deleted functions to private undefined ones
- chrome插件开发之:关于一些设定变量以及变量存储的问题
- 【字符串】翻转单词顺序
- tianchai 12023 水管工游戏(DFS搜索)
- 区块链中Blockchain