题目考察的知识点是:
贪心算法。
题目解答方法的文字分析:
我们可以遍历价格列表prices,同时维护一个变量minPrice表示到目前为止的最低价格,一个变量profit表示当前的最大利润。在遍历过程中,不断更新minPrice和profit。
本题解析所用的编程语言:
java语言。
完整且正确的编程代码:
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param prices int整型一维数组
* @return int整型
*/
public int max_profit (int[] prices) {
// write code here
int profit = 0;
int minp = prices[0];
for (int i = 1; i < prices.length; i++) {
if (prices[i] < minp) {
minp = prices[i];
} else {
profit = Math.max(profit, prices[i] - minp);
}
}
return profit;
}
}

京公网安备 11010502036488号