题目描述
链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/
You are given an integer array
prices
whereprices[i]
is the price of a given stock on theith
day.On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.
Find and return the *maximum** profit you can achieve*.
解释:
给定一个数组prices
,其中prices[i]
表示第i天的股票价格,股票可以当天买,也可以当天卖。但是注意:任何时候最多只能持有一只股票
求获取的最大利润?
基本思想
记录看到的提示:
- Don't overthink Solution is very simple. The solution simply iterates through the prices array, adding up the profit whenever a price increase is detected from one day to the next.
- The approach is to iterate through the prices array, identifying upward price movements, and accumulating the profit by adding the differences between consecutive days' prices.
只要判断是一个上升的趋势,利润即可累加。不要将其当成复杂的动态规划问题。
比如[1,2,3]
可以第一天买,第二天卖;第二天卖完,第三天买。或者 第一天买,第三天卖。两种方式本质上利润是一致的。只要是上升的趋势,则可。一旦上升的趋势终止,则要重新开始一个上升趋势,才能累计利润。
对于 [1,4,3,7]
最大利润是什么?是第一天买,第二天卖;第三天买,第四天卖。只要数组显示处于上升趋势,则利润可以增加。
时间复杂度\(O(n)\), 你以为很复杂其实很简单。对于任意一道题目,要有两种思维,简单和复杂。复杂走不通,也许就是简单。
代码
C++
int maxProfit(vector<int>& prices) {
int size = prices.size();
if (size<=1) return 0;
int res = 0;
for(int i=1;i<size;++i) {
if (prices[i]>prices[i-1]) { // 注意当天卖可以当天买回来
res += prices[i] - prices[i-1];
} // 其他情况不操作
}
return res;
}
python
def maxProfit(self, prices: List[int]) -> int:
n = len(prices)
if n <= 1: return 0
res = 0
for i in range(1, n):
if prices[i] > prices[i-1]:
res += prices[i] - prices[i-1]
return res
标签:Sell,Buy,int,res,II,prices,day,stock
From: https://www.cnblogs.com/douniwanli/p/18198648