LeetCode Best Time to Buy and Sell Stock
来源:互联网 发布:sql server2000 sp3 编辑:程序博客网 时间:2024/05/29 15:06
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.
i从小到大时,保存 <i 的最小的数,同时记录最大profit;
i从大到小时,保存 >i 的最大的数,同时记录最大profit。
class Solution {public:int maxProfit(vector<int> &prices) {if (prices.size() == 0)return 0;int min = prices[0], res = 0;for (unsigned i = 1; i < prices.size(); i++) {res = prices[i] - min > res ? prices[i] - min : res;min = prices[i] < min ? prices[i] : min;}return res;}};
class Solution {public:int maxProfit(vector<int> &prices) {if (prices.size() == 0)return 0;int max = prices[prices.size() - 1], res = 0;for (int i = prices.size() - 2; i >= 0; i--) {res = max - prices[i] > res ? max - prices[i] : res;max = prices[i] > max ? prices[i] : max;}return res;}};
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
- C++内存分配:堆和栈
- POJ 1442 Black Box(优先队列)
- iOS 下载图片前如何预取图片的大小
- 旅行,写作,编程 :IT文艺青年的生活态度
- [UVa 11440]Help Tomisu 数论 欧拉函数+拓欧逆元
- LeetCode Best Time to Buy and Sell Stock
- linux中sed命令替换包含引号、斜杠等特殊字符的的使用
- Linux Path
- android如何使用DOM来解析XML+如果做一个表情的弹出框
- STL--H - Black Box(两个优先队列,求第k小的值)
- 堆排序的非递归算法
- poj 1979 Red and Black
- HDU-1196
- POJ - 3041 Asteroids (二部图最大匹配 = 最小点覆盖)