题目描述:
思路:
此题使用动态规划求解。记录下前i - 1个数组元素中的最小值,最大差值就是前 i - 1 个元素的最大差值和当前元素减前i个数组元素中的最小值得到的差值中的大的那个。
即
前i天的最大收益 = max{前i-1天的最大收益,第i天的价格-前i-1天中的最小价格}
完整代码为:
class Solution {
public:
int max1(int a, int b)
{
return a > b? a:b;
}
int maxProfit(vector<int>& prices) {
if (prices.empty())
{
return 0;
}
int min = prices[0];
int max = 0;
for (int i = 0; i < (int)prices.size(); i++)
{
if (prices[i] < min)
{
min = prices[i];
}
max = max1(max, prices[i] - min);
}
return max;
}
};
时间复杂度: O(n)