Problem:
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
Solution1:
对数组进行遍历,一一比较
class Solution {
public int maxProfit(int[] prices) {
int max = 0;
for(int i = 0; i < prices.length; i++) {
for(int j = i + 1; j < prices.length; j++) {
if(prices[i] <= prices[j]) {
max = Math.max(prices[j] - prices[i], max);
}
}
}
return max;
}
}
Solution2:
寻找最小price,同时更新最大profit,只需要遍历一次
class Solution {
public int maxProfit(int[] prices) {
int minPrice = Integer.MAX_VALUE;
int maxProfit = 0;
for (int i = 0; i < prices.length; i++) {
if(prices[i] <= minPrice) {
minPrice = prices[i];
} else if(prices[i] - minPrice >= maxProfit) {
maxProfit = prices[i] - minPrice;
}
}
return maxProfit;
}
}
Extra Material: https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/solution/yi-ge-fang-fa-tuan-mie-6-dao-gu-piao-wen-ti-by-l-3/
475




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



