Best Time to Buy and Sell Stock
来源:互联网 发布:淘宝网q币充值软件 编辑:程序博客网 时间:2024/06/14 06:52
Best Time to Buy and Sell Stock
作者:money
标签:leetcode,C++
问题:
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: 5
max. 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: 0
In this case, no transaction is done, i.e. max profit = 0.
分析
按照信息论的感觉,这道题复杂度应该为
使用两个指针:
其中必然有:
当出现
my solution
class Solution {public: int maxProfit(vector<int>& prices) { int i=0,j=1,maxi=j; int max=0; for(i=0;j<prices.size();) if(prices[i]>prices[j]||j==prices.size()) { i=j; j++; } else { if(max<prices[j]-prices[i]) max=prices[j]-prices[i]; j++; } return max; }};
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
- centos 配置网卡
- strtok()函数的实现
- HDU 3533 广搜
- 解读USR-TCP232-Test测试软件只链接发送不显示问题
- 机器学习(周志华) 参考答案 第三章 线性模型 3.5
- Best Time to Buy and Sell Stock
- ROS(indigo)一个简单灵活和可扩展的2D多机器人仿真器stdr_simulator
- SGU326 perspective 最大流 竞赛排名问题
- python3 比较两个list的结构
- poj 1860 Currency Exchange
- Android应用优化过程分析
- Codeforces Round #271 (Div. 2) F 线段树+pair
- 红黑树(插入)
- [2016ACM多校] HDU5768 容斥原理 中国剩余定理