LeetCode 122: Best Time to Buy and Sell Stock 2 解题与思考
题目描述
相比上一道题,这次你可以买很多次,但是你每次最多只能持有一只股票:你在抛出上一只股票之前无法买下一只。求最大利润
思路
一旦即将降价就抛售,即将升价就买入,没什么好说的
算法
顺序遍历数组,记录一下是否上升下降,是否需要买入卖出
代码
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int maxProfit(vector<int>& prices) {
if ( prices.size() == 0 ) return 0;
int P = 0, last = prices[0];
bool isRising = (prices[0] > prices[1]) ? false : true;
for ( auto i = prices.begin(); i != prices.end(); i++ ) {
if ( isRising ) {
if ( i + 1 == prices.end() )P += *i- last;
else {
if ( *i > *(i + 1) ) {
P += *i - last;
isRising = false;
}
}
}
else {
if ( i + 1 == prices.end() );
else {
if ( *i < *(i + 1) ) {
last = *i;
isRising = true;
}
}
}
}
return P;
}
};
思考
同样是一道easy,因为是一个系列顺带打完它