1.题目描述
2.思路
思路1:
3.java代码实现
class Solution {
public int maxProfit(int[] prices) {
// //初始化最小价格为最大值,最大利润为0
// int minPrice=Integer.MAX_VALUE;
// int maxProfit=0;
// //遍历价格数组
// for (int price : prices)
// {
// //如果当前价格更低,更新最小价格
// if(price<minPrice)
// {
// minPrice = price;
// }
// // 计算当前卖出时的利润
// else
// {
// int profit=price-minPrice;
// // 更新更大利润
// if(profit>maxProfit)
// {
// maxProfit= profit;
// }
// }
// }
// return maxProfit;
if(prices==null ||prices.length<2)
{
return 0;
}
int minPrice=prices[0];// 初始化最小价格为第一个元素
int maxPofit=0;
for(int i=1;i<prices.length;i++)
{
// 如果当前价格比最小价格大,计算利润
int profit=prices[i]-minPrice;
// 更新最小价格
minPrice = Math.min(minPrice,prices[i]);
// 更新最大利润
maxPofit = Math.max(maxPofit,profit);
}
return maxPofit;
}
}