题目描述
这题被归纳为了动规,但好像往动规的方向思考,没有思路,索性用原始一点的方法
首次提交
代码
public static int maxProfit(int[] prices)
{
int len ;
if (prices == null || (len = prices.length) == 0) { return 0; }
int min = prices[0];
int diff = 0;
for (int i = 1; i < len; i++)
{
diff = diff > prices[i] - min? diff: prices[i] - min;
if (min > prices[i]) { min = prices[i]; }
}
return diff;
}
提交结果
看起来还不错的样子
官方题解
代码
public int maxProfit(int[] prices)
{
int minprice = Integer.MAX_VALUE;
int maxprofit = 0;
for (int i = 0; i < prices.length; i++)
{
if (prices[i] < minprice)
minprice = prices[i];
else if (prices[i] - minprice > maxprofit)
maxprofit = prices[i] - minprice;
}
return maxprofit;
}
提交结果
效果好像差不多,可能对于太简单的题,算法对于性能的优化效果就没那么大