可以采用贪心算法,题中说要获得最大利润,那就要在最低点买入,最高点卖出。且最高点要是买入后的最高点。代码如下
class Solution {
public int maxProfit(int[] prices) {
//买入的价格
int cost = Integer.MAX_VALUE;
//利润
int profit = 0;
for(int price : prices){
cost = Math.min(cost,price);
profit = Math.max(profit,price-cost);
}
return profit;
}
}
for循环逐项对比,从而找出最小的花费和最大的利润。
复杂度分析
时间复杂度 O(N) : 其中 N为数组 prices 长度。遍历 prices 使用线性时间。
空间复杂度 O(1) : 变量 cost , profit 使用 O(1) 空间。
261

被折叠的 条评论
为什么被折叠?



