import java.util.*;
public class Solution {
/**
*
* @param prices int整型一维数组
* @return int整型
*/
public int maxProfit (int[] prices) {
// write code here
if (prices == null || prices.length == 0) return 0;
// 记录扫描的最小价格
int minPrice = prices[0];
// 记录扫描过的最大利润
int maxPorfit = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] < minPrice) {
// 比前面还小,则把最小利润重置
minPrice = prices[i];
} else {
// 计算第i天利润,求出这一天最大利润然后重置最大利润记录
maxPorfit = Math.max(maxPorfit, prices[i] - minPrice);
}
}
return maxPorfit;
}
}
解题思想:扫描记录最小值及最大收益,不断遍历重置两个值

京公网安备 11010502036488号