121. 买卖股票的最佳时机

题目链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/submissions/

执行用时:1 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗:51.2 MB, 在所有 Java 提交中击败了79.45%的用户

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public int maxProfit(int[] prices) {
int minPrice = 100001, profit = 0;
int length = prices.length;
for(int i = 0; i < length; i++) {
if (minPrice > prices[i]) {
minPrice = prices[i];
} else if (prices[i] - minPrice > profit) {
profit = prices[i] - minPrice;
}
}
return profit;
}
}

Swift

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
func maxProfit(_ prices: [Int]) -> Int {
var profit = 0 //记录最大利润
var minValue: Int = prices[0] //记录数组中访问过的最小值
let n = prices.count
for i in 0 ..< n {
minValue = min(minValue, prices[i])
profit = max(prices[i] - minValue, profit)
}
return profit
}
}

121. 买卖股票的最佳时机
https://pisces34.github.io/2022/01/11/leetcode/121/
发布于
2022年1月11日
许可协议