Best Time to Buy and Sell Stock
来源:互联网 发布:经典网络言情小说 编辑:程序博客网 时间:2024/05/16 14:20
一、问题描述
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.
Example 1:
Input: [7, 1, 5, 3, 6, 4]Output: 5max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example 2:
Input: [7, 6, 4, 3, 1]Output: 0In this case, no transaction is done, i.e. max profit = 0.
二、思路
动态规划法求解。
在双层循环中,记录当前出现过的最低价格min_price,作为买入价格,并计算以当天价格出售的收益,作为可能的最大收益max_price,整个遍历过程中,出现过的最大收益max_price就是所求。
三、代码
class Solution {public: int maxProfit(vector<int> &prices) { // Start typing your C/C++ solution below // DO NOT write int main() function if (prices.size() == 0) return 0; int maxPrice = prices[prices.size()-1]; int ans = 0; for(int i = prices.size() - 1; i >= 0; i--) { maxPrice = max(maxPrice, prices[i]); ans = max(ans, maxPrice - prices[i]); } return ans; }};
0 0
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time To Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- 《程序是怎样跑起来的》读书笔记 之 第三章 计算机进行小数运算时出错的原因
- 909422229__JavaScript基本用法及注意事项总结
- 学习scrapy——介绍&安装
- 什么是问题
- java对象循环依赖问题
- Best Time to Buy and Sell Stock
- Java学习中的乱码问题
- jni
- 推荐几个比较好的:Json解析的网络源文件连接
- NHibernate查询导致Update问题
- Apache ServiceMix-003-技术选择指导
- 在对设置表格设置table-layer:fixed样式后,发现表格中有一行合并过,其它没有合并的行的列宽会平均化,对列宽的设置会失效
- 136.[LeetCode] Single Number
- ViewController 生命周期