1.题目描述
2.思路
思路1:
做两轮排序,第一轮排序找到最小的那个数,然后再判断最小的那个数之后还有其他数吗,如果有在进行排序,选出最大的那个数,然后值相减。
问题要点:
(1)你需要找到一个买入和卖出的时间点,使得卖出的价格大于买入的价格,从而最大化利润。
(2)如果数组中的股票价格是递减的,你不能获得任何利润,此时最大利润为 0。
思路2:
3.代码实现
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;
}
}