[Medium]Best Time to Buy and Sell Stock II
来源:互联网 发布:淘宝商家开通花呗 编辑:程序博客网 时间:2024/05/29 07:39
问题:
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 n = prices.size(); int ans = 0; int k = 0; for (int i = 0; i < n-1; ++i) { if (k && prices[i+1] < prices[i]) {ans += prices[i]; k = 0;} if (!k && prices[i+1] > prices[i]) {ans -= prices[i]; k = 1;} } if (k) ans += prices[n-1]; return ans; }};
0 0
- [Medium]Best Time to Buy and Sell Stock II
- [Medium]Best Time to Buy and Sell Stock with Cooldown
- [Leetcode 122, Medium] Best Time to Buy and Sell Stock II
- 122.leetcode Best Time to Buy and Sell Stock II(medium)[贪心算法 数组]
- 122. Best Time to Buy and Sell Stock II [medium] (Python)
- Leetcode 122. Best Time to Buy and Sell Stock II (Medium) (cpp)
- Medium 122题 Best Time to Buy and Sell Stock II
- 122. Best Time to Buy and Sell Stock II 类别:贪心算法 难度:medium
- LeetCode解题报告 122. Best Time to Buy and Sell Stock II [medium]
- [LeetCode]Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock II
- Leetcode: Best Time to Buy and Sell Stock II
- [Leetcode] Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock II
- LeetCode : Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock II
- [LeetCode] Best Time to Buy and Sell Stock II
- leetcode 61: Best Time to Buy and Sell Stock II
- [Easy]House Robber
- Pip源
- 文章标题
- JPA配置文档persistence.xml文件的参数说明
- [Medium]House Robber III
- [Medium]Best Time to Buy and Sell Stock II
- 盘点|回顾2016华为与交通行业的“最美旅程”
- 笔记——2
- 我的第一个java-web项目之路:(一)需求分析.
- Spring Data JPA入门
- 【JavaScript的基础知识总结】
- opencv读写图片,分离通道等操作
- 算法4-二分查找
- HTML5文档结构分析