LeetCode | Best Time to Buy and Sell Stock II(股票购买抛售问题II)
2014-08-15 11:36
381 查看
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).
题目解析:
可以买很多次,求最大收益。
通过画图可以得出,求的是波浪线的上升线段的长度值。所以当a[i]>a[i-1]的时候,res就增加差值。
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).
题目解析:
可以买很多次,求最大收益。
通过画图可以得出,求的是波浪线的上升线段的长度值。所以当a[i]>a[i-1]的时候,res就增加差值。
class Solution { public: int maxProfit(vector<int> &prices) { int n = prices.size(); if(n == 0 || n == 1) return 0; int res = 0; for(int i = 1;i < n;i++){ if(prices[i] > prices[i-1]) res += prices[i]-prices[i-1]; } return res; } };
相关文章推荐
- LeetCode | Best Time to Buy and Sell Stock III(股票购买抛售问题III)
- LeetCode | Best Time to Buy and Sell Stock(股票购买和抛售问题)
- LeetCode——Best Time to Buy and Sell Stock II (股票买卖时机问题2)
- LeetCode 122 Best Time to Buy and Sell Stock II(股票买入卖出的最佳时间 II)
- [Leetcode] Best time to buy and sell stock ii 买卖股票的最佳时机
- Best Time to Buy and Sell Stock II 最佳时间买入卖出股票(多次买卖)@LeetCode
- [LeetCode] Best Time to Buy and Sell Stock I II III IV 股票买卖
- best-time-to-buy-and-sell-stock(购买并抛售股票的最佳时机)
- [LeetCode 122] - 买入与卖出股票的最佳时机II(Best Time to Buy and Sell Stock II)
- LeetCode 122 Best Time to Buy and Sell Stock II(股票买入卖出的最佳时间 II)
- LeetCode——Best Time to Buy and Sell Stock I (股票买卖时机问题1)
- LeetCode——Best Time to Buy and Sell Stock III (股票买卖时机问题3)
- 【Leetcode】:122. Best Time to Buy and Sell Stock II 问题 in JAVA
- LeetCode 122 Best Time to Buy and Sell Stock II(股票买入卖出的最佳时间 II)
- LeetCode-714:Best Time to Buy and Sell Stock with Transaction Fee (带有抛售费用的股票最大利润) -- medium
- Leetcode 122 Best Time to Buy and Sell Stock II 不限次数买卖股票最大收益
- leetcode之Best Time to Buy and Sell Stock II问题
- 【启发】leetcode - 121. Best Time to Buy and Sell Stock 【动态规划 + 连续区间问题 + 试探性购买】
- 【LeetCode】【Python解决问题的方法】Best Time to Buy and Sell Stock II
- [LeetCode 121] - 买入与卖出股票的最佳时机(Best Time to Buy and Sell Stock)