题目链接:https://leetcode-cn.com/problems/gu-piao-de-zui-da-li-run-lcof/

题目解析
-
暴力解析,两次
for循环
计算。
代码省略
复杂度分析
空间复杂度: O(n^2)。
时间复杂度: O(1)。 -
一次遍历,遍历的时候记录
最小的值
和当前计算得到最大的结果
即可。
public int maxProfit(int[] prices) {
if (prices == null){
return 0;
}
int max = 0;
int min = Integer.MAX_VALUE;
for (int price : prices) {
if (price < min){
min = price;
}else {
max = Math.max(max,price-min);
}
}
return max;
}
复杂度分析
空间复杂度: O(n)。
时间复杂度: O(1)。
网友评论