LeetCode-Best Time to Buy and Sell Stock
来源:互联网 发布:调节手机光线软件 编辑:程序博客网 时间:2024/06/04 23:35
题目
给定一个数组,数组中的第i个元素表示股票在第i天的价格。如果有一次交易的机会(一次买,一次卖),设计一种算法来找到最大的收益(售价-进价)。
示例
输入:[21, 13, 16, 28, 16, 45, 23, 1, 24, 40, 23];
输出:39
输入: 输出:
0
输入:[10, 9, 8, 7, 6];
输出:0
分析
方法1:
最简单的思路就是双重for循环,取任意两个数的差值,找到最大的差值。
然而,这种方法的效率不高,超时,因此需要一种更高效的办法。
方法2:
首先,卖肯定在买之后;卖的越高,买的越低,收益越高。因此,只需遍历所有价格,判断当前价格减去在此之前的最小价格的收益是否大于此前的收益。而当前价格之前的最小价格在遍历所有价格的过程中也可以同时求得。
以示例中的第一个为例:
当i = 4时(从1开始),此前的最大收益为0,最小价格为13。此时价格为28,所以此时最大收益为15,最小价格不变,认为13
当i = 8时,此前最大收益为32,最小价格为13,当前价格为1,所以此时最大收益不变,最小价格为1
当i = 10时,此前最大收益32,最小价格1,当前价格40,所以此时最大收益39,最小价格1
流程
- 判断数组元素个数是否大于1。否,返回0
- 初始化最大收益为0,当前最小值为第一个元素值
- 从第二个元素开始遍历
- 更新最大收益
- 更新当前最小价格
代码
int maxProfit(vector<int> &prices){ if (prices.size() <= 1) return 0; int iMaxProfit = 0; vector<int>::iterator iterBuy = prices.begin(); vector<int>::iterator iterSell; for (; iterBuy != prices.end() - 1; iterBuy++) { for (iterSell = iterBuy + 1; iterSell != prices.end(); iterSell++) { int iPrice = iMaxProfit + *iterBuy; if (*iterSell > iPrice) iMaxProfit = *iterSell - *iterBuy; } } return iMaxProfit;}int maxProfitOpt(vector<int> &prices){ if (prices.size() <= 1) return 0; int iMaxProfit = 0; // 收益 vector<int>::iterator iterMin = prices.begin(); vector<int>::iterator iterSell = prices.begin() + 1; int iCurMin = *iterMin; // 当前最小 for (; iterSell != prices.end(); iterSell++) { iMaxProfit = max(iMaxProfit, *iterSell - iCurMin); iCurMin = min(iCurMin, *iterSell); } return iMaxProfit;}
完整代码
GitHub
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++设计一个真正不能被继承的类
- 初识GihHub,创建仓库,使用GitHub for Windows 同步本地代码文件,创建分支
- Ruby on Rails创建项目和服务启动中的一些问题
- FZU 2186 BFS+状压最短路
- Hdoj 1719 Friend 【数学】
- LeetCode-Best Time to Buy and Sell Stock
- Android 上传图片至服务器
- PLSQL Developer用户登录时提示:ORA-28000: the account is locked
- AsyncTask、View.post(Runnable)、ViewTreeObserver三种方式总结frame animation自动启动
- C++中的this指针
- Linux软件的安装和卸载
- Manacher算法(最长子回文串)
- css抖动基础
- 整数换为字符串