class Solution {
public int maxProfit(int[] prices) {
// 令价格最小值为 Integer.MAX_VALUE
int minprice = Integer.MAX_VALUE;
// 令最大收益为 0
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;
}
}
leetcode原题: 121. 买卖股票的最佳时机
首先设置最小价格为 Integer.MAX_VALUE,这样才能无论如何数组的第一个值都小于最小价格,才能完成下一步的赋值。同时初始化最大收益为 0.
循环找出最小的价格过程中也计算着最大收益,最后返回最大收益。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有