LeetCode 121. Best Time to Buy and Sell Stock [Easy]

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

题目难度:Easy

解答1[Java]:

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

思路

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