leetcode-股票最大盈利值-动态规划
基本思路
每天卖出股票的最优价格 == 之前最低价格和当天价格的差值
if (prices[i]-prices[i-1]+dp[i-1]<0) //说明当日的价格比之前的最低价格还要低,所以改成当日买入并且使dp[i] = o
dp[i] = 0;
else
dp[i] = prices[i]-prices[i-1]+dp[i-1];
dp[I]代表了每日卖出股票的局部优解,最优解并不一定要在当天卖出。
使用max来记录最优解
int maxProfit(int* prices, int pricesSize){
int *dp = (int *)calloc(pricesSize, sizeof(int));
int max = 0;
for (int i = 1; i < pricesSize; i++)
{
if (prices[i] - prices[i-1] + dp[i-1] <= 0)
dp[i] = 0;
else
dp[i] = prices[i] - prices[i-1] + dp[i-1];
max = max>dp[i]?max:dp[i];
}
return max;
}
int maxProfit(int* prices, int pricesSize){
int i;
int min, max;
min = *prices;
max = 0;
if (pricesSize < 2)
return 0;
for (i = 0; i < pricesSize; i++)
{
if (min > *(prices+i))
min = *(prices+i);
if (*(prices+i) - min > max)
max = *(prices+i) - min;
}
return max;
}