知识点
贪心
解题思路
定义两个变量:minPrice表示前i天中的最低价格,maxProfit表示前i天中的最大利润。
我们可以从前往后遍历价格数组prices。对于第i天,如果prices[i]比minPrice更低,我们可以更新minPrice的值。如果prices[i]比minPrice更高,我们可以计算当前利润,即prices[i] - minPrice,并更新maxProfit的值。
Java题解
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param prices int整型一维数组
* @return int整型
*/
public int max_profit (int[] prices) {
// write code here
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;
}
}



京公网安备 11010502036488号