122. Best Time to Buy and Sell Stock II - LeetCode

122. Best Time to Buy and Sell Stock II - LeetCode

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 (i.e., buy one and sell one share of the stock multiple times).

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

Solution:

class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.size() == 0 || prices.size() == 1) return 0;
int profit = 0, flag = 0, min;
for (int i = 1; i < prices.size(); i++) {
if (!flag && prices[i] > prices[i-1]) {
min = prices[i-1]; flag = 1;
} else if (flag) {
if (prices[i] < prices[i-1]) {
profit += prices[i-1] - min; flag = 0;
} else if (i == prices.size() - 1) {
profit += prices[i] - min;
}
}
}
return profit;
}
};

/*
Wrong answer
Input:
[1,2]
Output:
0
Expected:
1
*/

没有注意到判断出最低点时, 当前点已经时最高点的情况.

// Time:O(n), Space:O(1)
class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.size() == 0 || prices.size() == 1) return 0;
int profit = 0, flag = 0, min;
for (int i = 1; i < prices.size(); i++) {
if (!flag && prices[i] > prices[i-1]) {
min = prices[i-1]; flag = 1;
if (i == prices.size()-1) {
profit += prices[i] - min;
}
} else if (flag) {
if (prices[i] < prices[i-1]) {
profit += prices[i-1] - min; flag = 0;
} else if (i == prices.size() - 1) {
profit += prices[i] - min;
}
}
}
return profit;
}
};