LeetCode算法解题集: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).
思路:
低买高卖,贪心算法。每次判断是否需要买和卖的时候,都要用当前的值和下一个值比较,如果有利可图,则操作;否则,不处理。算法复杂度:O(n)
代码:
class Solution {
public:
const int NULL_PRICE = -1;
int maxProfit(vector<int>& prices) {
unsigned int max_limit = prices.size();
int buy_price = NULL_PRICE;
int max_profit = 0;
for (unsigned int i = 0; i < max_limit; i++)
{
if ((i + 1) >= max_limit)
{
break;
}
int total_price = prices[i];
int tomorrow_prive = prices[i + 1];
if (total_price > tomorrow_prive)
{
if (buy_price != NULL_PRICE)
{
max_profit += total_price - buy_price;
buy_price = NULL_PRICE;
}
}
if (total_price < tomorrow_prive)
{
if (buy_price == NULL_PRICE)
{
buy_price = total_price;
}
}
}
if (buy_price != NULL_PRICE)
{
max_profit += prices[max_limit - 1] - buy_price;
}
return max_profit;
}
};
总结:
1、思路比较简单,主要用到的是贪心算法,即局部最优。
2、注意最小值有可能为0。