121. Best Time to Buy and Sell Stock
来源:互联网 发布:上交所网络投票系统 编辑:程序博客网 时间:2024/06/08 16:03
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.
class Solution {public: int maxProfit(vector<int>& prices) { if(prices.size()==0) return 0; else { int minBuy = prices[0]; int maxProfit = 0; for(int i=1;i<prices.size();i++) { minBuy = min(minBuy,prices[i]); if(prices[i]-minBuy > maxProfit) maxProfit = prices[i]-minBuy; } return maxProfit; } }};
阅读全文
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
- 网络加载图片
- 牛顿迭代法-朋友Z与方程
- HDU5781 ATM Mechine (概率dp)
- 如何使用py2exe,以及解决ImportError: No module named py2exe问题
- jasperreports中图片的填充方式
- 121. Best Time to Buy and Sell Stock
- Linux压缩解压最常用3个命令及详解
- Java面向对象的三大特性
- 编程感受
- spring 注解学习
- JVM(1):Java 类的加载机制
- 通过继承TagSupport编写标签的方法
- 仿IOS风格的搜索框
- HA集群(nginx )