leetcode Best Time to Buy and Sell Stock II
来源:互联网 发布:新网互联域名如何续费 编辑:程序博客网 时间:2024/06/06 12:47
题目
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).
题目链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
一个数组里面存放着一支股票每天的价格。你可以做多次交易,也就是买卖多次。但是你必须在买入之前先把手里的股票卖掉。求最大收益。
分析
- 如果今天的价格比前一天低,前一天就不买入;
- 如果今天的价格比前一天高,我们就前一天买入,今天卖出。
- 遍历数组,将利润相加。
代码
class Solution {public: int maxProfit(vector<int>& prices) { int len = prices.size(); if(len <= 0) return 0; int max_profit = 0; int buy_price = prices[0]; for(int i = 0; i < len; i++){ if(prices[i] < buy_price) buy_price = prices[i];//今天比之前的价格低,相当于前一天没买。 if(prices[i] > buy_price){ max_profit += (prices[i] - buy_price); buy_price = prices[i];//并不代表着一定会买入,取决于以后的价格。 } } return max_profit; }};
0 0
- [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
- 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
- [LeetCode] Best time to buy and sell a 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]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-Best Time to Buy and Sell Stock II
- [leetcode] Best Time to Buy and Sell Stock II
- 并发趣味问题之ABC
- Android Studio
- 大牛博士是如何进行文献检索和阅读的
- swiper滑动实现幻灯片功能及swiper animate的动画特效
- JAVA关键字 static,finally
- leetcode Best Time to Buy and Sell Stock II
- JMS介绍:我对JMS的理解和认识
- 为什么nova计算节点上报的剩余磁盘空间为负数?
- image等比缩小
- android开发官方教程之Building a Dynamic UI with Fragments
- USACO3.2--Magic Squares+经典搜索
- Ubuntu1204下安装FreeSurfer使用Qdec时报libXss.so.1的问题的解决办法
- UITextField 文本字段控件 -- IOS (解决键盘遮住View及密文設定的问题)(实例)
- 一些格式的工具类(非常全面哦!)