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).
思路:遍历数组,如果数组下一位的值大于这一位,若此时手上没有股票,则买入。有则什么都不做。若下一位的值小于这一位,若此时手上有股票,则卖出股票,没有则什么都不做。
代码:
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int maxProfit(vector<int>& prices) {
bool have = 0;
int buy_price;
int benifit = 0;
for (int i = 0; i < prices.size(); i++) {
if (i != prices.size() - 1) {
if (prices[i] < prices[i + 1]) {
if (!have) {
have = 1;
buy_price = prices[i];
}
}
else {
if (have) {
have = 0;
benifit += prices[i] - buy_price;
}
}
}
else {
if (have) {
benifit += prices[i] - buy_price;
have = 0;
}
}
}
return benifit;
}
};