给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0
https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/
示例1:
示例2:
提示:
Java解法
package sj.shimmer.algorithm.m3_2021;
/**
* Created by SJ on 2021/3/27.
*/
class D59 {
public static void main(String[] args) {
System.out.println(maxProfit(new int[]{7, 1, 5, 3, 6, 4}));
System.out.println(maxProfit(new int[]{7, 6, 4, 3, 1}));
}
public static int maxProfit(int[] prices) {
int result = 0;
if (prices != null && prices.length > 1) {
int length = prices.length;
int min = 0;
int max = 0;
for (int i = 0; i < length; i++) {
if (prices[i] < prices[min]) {
result = Math.max(result, prices[max] - prices[min]);
max = i;
min = i;
}
if (prices[i] > prices[max]) {
max = i;
}
}
result = Math.max(result, prices[max] - prices[min]);//最后一段最大利润
}
return result;
}
}
官方解
-
暴力法
- 时间复杂度:O(n^2)
- 空间复杂度:O(1)
-
一次遍历
- 时间复杂度:O(n)
- 空间复杂度:O(1)