LeetCode 121. Best Time to Buy and Sell Stock
来源:互联网 发布:解放军纪律知乎 编辑:程序博客网 时间:2024/06/01 22:14
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) { int profit = 0; int len = prices.size(); if(len == 0) return 0; int minprice = prices[0]; int i; for(i = 1; i < len; i ++){ if((prices[i] - minprice) > profit) profit = prices[i] - minprice; else if(prices[i] < minprice) minprice = prices[i]; } return profit; }};
0 0
- LeetCode 121. Best Time to Buy and Sell Stock
- [Leetcode] 121. Best Time to Buy and Sell Stock
- [leetcode] 121. Best Time to Buy and Sell Stock
- 【leetcode】121. Best Time to Buy and Sell Stock
- [leetcode] 121. Best Time to Buy and Sell Stock
- 121. Best Time to Buy and Sell Stock LeetCode
- [LeetCode]121. Best Time to Buy and Sell Stock
- Leetcode 121. Best Time to Buy and Sell Stock
- leetcode 121. Best Time to Buy and Sell Stock
- LeetCode 121. Best Time to Buy and Sell Stock
- LeetCode题解:121. Best Time to Buy and Sell Stock
- LeetCode *** 121. Best Time to Buy and Sell Stock
- 【leetcode】121. Best Time to Buy and Sell Stock
- #leetcode#121. Best Time to Buy and Sell Stock
- LeetCode 121. Best Time to Buy and Sell Stock
- 121.[Leetcode]Best Time to Buy and Sell Stock
- leetcode 121. Best Time to Buy and Sell Stock
- Leetcode 121. Best Time to Buy and Sell Stock
- Android 小知识点汇总(更新中)
- org.apache.struts.action.InvalidCancelException异常解决方法
- POJ 2440 DNA
- 关于ListView的显示问题
- The number of method references in a .dex file cannot exceed 64K
- LeetCode 121. Best Time to Buy and Sell Stock
- windows安装配置mysql-5.7.13-winx64方法
- maven如何手动导入ojdbc6.jar或ojdbc14
- Mondrian 4 测试的简单demo(Saiku简单测试Schema文件)
- python网络天气爬虫
- HDU 4408 Minimum Spanning Tree(最小生成树计数)
- 防止sql注入
- Gym 101028G-The Tower of Evil
- Canvas之绘制基本形状