leetcode 121. best time to buy and sell stock [easy] 思路

题目来源:https://leetcode.com/problems/best-time-to-buy-and-sell-stock

题目难度:Easy

1
2
3
4
5
6
7
8
9
10
11
12
13
public class  {
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;
}
}

思路

涉及两个变量,一个存储截至目前最小的值,一个存储截至目前最大的利润。