【leetcode】Best Time to Buy and Sell Stock II

时间:2022-03-17 08:50:15

Best Time to Buy and Sell Stock II

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).

其核心就是找到所有的单调递增区间,然后卖出去
 
最简单的,每当有涨价,就卖出去,累加所有收益(Accept了,不过似乎 buy one and sell one share of the stock multiple times了)
 
 class Solution {
public:
int maxProfit(vector<int> &prices) { int profit=;
for(int i=;i<prices.size();i++)
{
if(prices[i]>prices[i-])
{
profit+=prices[i]-prices[i-];
}
}
return profit; }
};

 

 
下面代码找到了递增的区间,然后在最后一天卖出
 class Solution {
public:
int maxProfit(vector<int> &prices) { int profit=;
int n=prices.size(); if(n==)
{
return ;
}
int buyPrice=prices[]; for(int i=;i<n;i++)
{
if(prices[i]<prices[i-])
{
profit+=prices[i-]-buyPrice;
buyPrice=prices[i];
}
} profit+=prices[n-]-buyPrice; return profit; }
};