思路:
因为值允许买卖一次,所以本质上就是找数组里面最大值和最小值的差值(但是由于先买后卖原则,最小值必须出现在最大值的左边),所以从前往后开始遍历即可;
定义两个变量:
- 一个是用来保存最低价格,初始值为第一天的价格;
- 一个是用来记录最大的利润;
遍历数组,如果当前价格,低于最低价格,更新最低价格,如果不低于更新最大利润;
import java.util.*;
public class Solution {
/**
*
* @param prices int整型一维数组
* @return int整型
*/
public int maxProfit (int[] prices) {
// write code here
int len = prices.length;
// 记录最低价格
int minPrice = prices[0];
// 记录最大利润
int maxProfit = 0;
for(int i = 1; i<len; i++){
// 如果当前价格比最低的价格还要低,那么更新最低价格;
if(prices[i] < minPrice){
minPrice = prices[i];
}
// 然后,更新最大利润
maxProfit = Math.max(maxProfit, prices[i] - minPrice);
}
return maxProfit;
}
}
京公网安备 11010502036488号