题解 | #牛群售价预测#
牛群售价预测
https://www.nowcoder.com/practice/bbdb8d6f3a2e434e87f749358d16d653
知识点:贪心
我们要想获得最大的利润,就需要找到当前最小的元素,再用当前位置的元素减去最小的元素值,即为利润,要想利润最大,就需要保证我们的成本保持在最小值,通过不断更新最小成本,来尝试获取每个位置能得到的最大利润。
Java题解如下
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param prices int整型一维数组
* @return int整型
*/
public int max_profit (int[] prices) {
// write code here
int n = prices.length;
int profit = 0;
int min = prices[0];
for(int i = 1; i < n; i++) {
profit = Math.max(profit, prices[i] - min);
if(prices[i] < min) {
min = prices[i];
}
}
return profit;
}
}

