题解 | #牛群售价预测#
牛群售价预测
https://www.nowcoder.com/practice/bbdb8d6f3a2e434e87f749358d16d653
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param prices int整型一维数组
* @return int整型
*/
public int max_profit (int[] prices) {
// write code here
int profit = 0;
int right = prices[prices.length-1];
for(int i=prices.length-2;i>=0;i--){
if(prices[i]<right){
profit = Math.max(profit,right-prices[i]);
}else if(prices[i]>right){
right = prices[i];
}
}
return profit;
}
}
本题考察的知识点是贪心算法,所用编程语言是java。
我的想法是从后往前找从i位置之后的最大值,然后两者相减,就是在i位置买入股票售卖能够得到的最大利润
查看22道真题和解析