买卖股票的最佳时机
121. 买卖股票的最佳时机 - 力扣(LeetCode)
public class LeetCode121 {// 动态规划解法public int maxProfit(int[] prices) {int minPrice = Integer.MAX_VALUE;//最小价格,初始化为一个较大的数int maxProfit = 0;//最大利润,初始化为0for (int i = 0; i < prices.length; i++) {if (prices[i] < minPrice) {minPrice = prices[i];} else {maxProfit = Math.max(maxProfit, prices[i] - minPrice);}}//时间复杂度O(n)return maxProfit;}// 暴力解法public int maxProfit2(int[] prices) {int max = 0;for (int i = 0; i < prices.length - 1; i++) {for (int j = i + 1; j < prices.length; j++) {if (prices[j] > prices[i]) {max = Math.max(max, prices[j] - prices[i]);}}}//时间复杂度O(n^2)return max;}
}