LeetCode122. Best Time to Buy and Sell Stock II
来源:互联网 发布:固定资产标签软件 编辑:程序博客网 时间:2024/05/27 14:13
原题:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
此题将求最大利润改为求最大累计利润;
当当前价格高于先前售出价格时,立即在先前售出价格改为当前价格;
当当前价格小于先前售出价格时,立即在先前售出价格时售出,并于当前买入;
当当前价格小于先前买入价格时,立即在先前售出价格时售出,并于当前买入。
class Solution {public: int maxProfit(vector<int>& prices) { int buy = 0, sell = 0, n = 0, sum = 0; for (int i = 0; i < prices.size(); i++) { if (prices[i] >= prices[sell]) { sell = i; if (i == prices.size()-1) sum += prices[sell] - prices[buy]; } else if (prices[i] < prices[sell]||prices[buy] > prices[i]) { sum += prices[sell] - prices[buy]; buy = i; sell = buy; } } return max(n, sum); }};
198 / 198 test cases passed.
Status: Accepted
Runtime: 6 ms
阅读全文
0 0
- leetcode122---Best Time to Buy and Sell Stock II
- LeetCode122:Best Time to Buy and Sell Stock II
- leetcode122 Best Time to Buy and Sell Stock II
- LeetCode122. Best Time to Buy and Sell Stock II
- leetcode122 Best Time to Buy and Sell Stock II
- Leetcode122. Best Time to Buy and Sell Stock II
- leetcode122.[DP] Best Time to Buy and Sell Stock II
- LeetCode122—Best Time to Buy and Sell Stock II
- leetcode122. Best Time to Buy and Sell Stock II
- leetcode122~Best Time to Buy and Sell Stock II
- LeetCode122. Best Time to Buy and Sell Stock II题解
- LeetCode122 Best Time to Buy and Sell Stock II
- Leetcode122. Best Time to Buy and Sell Stock II
- LeetCode122. Best Time to Buy and Sell Stock II
- LeetCode122. Best Time to Buy and Sell Stock II
- LeetCode122. Best Time to Buy and Sell Stock II
- LeetCode122——Best Time to Buy and Sell Stock II
- Leetcode122 - Best Time to Buy and Sell Stock II (dp)
- monkey命令行参数详解
- mybatis框架的mapper.xml文件中sql的使用方法:
- MFC类图
- Android混淆
- ioctlsocket函数全面解析
- LeetCode122. Best Time to Buy and Sell Stock II
- js导出excel, 并解决文件名是随机的问题,兼容多个浏览器
- windows安装paramiko--- 以及依赖模块pycrypto
- Android vector标签 PathData
- 世界冠军 | 腾讯AI Lab斩获知识图谱顶级赛事KBP 2017世界冠军
- Flyway的“坑”
- java 单链表 添加 插入 删除
- 标签绑定click事件,ios手机系统下微信公众号页面标签点击失效
- hibernate系列十一:一对一关联配置及案例