题解 | #牛群买卖计划#
牛群买卖计划
https://www.nowcoder.com/practice/3e4ae511b4a941b788da5077b08a7d07?tpId=354&tqId=10595790&ru=/exam/oj&qru=/ta/interview-202-top/question-ranking&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D354
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param prices int整型一维数组
* @return int整型
*/
public int maxProfit (int[] prices) {
int buy1 = Integer.MAX_VALUE;
int buy2 = Integer.MAX_VALUE;
int buy3 = Integer.MAX_VALUE;
int sell1=0;int sell2=0;int sell3=0;
for(int i=0;i<prices.length;i++){
// 取最小购入
buy1 = Math.min(buy1, prices[i]);
// 最大卖出利润
sell1 = Math.max(sell1, prices[i] - buy1);
// 第一次买卖的基础上取最小购入
buy2 = Math.min(buy2, prices[i] - sell1);
// 取最大卖出
sell2 = Math.max(sell2, prices[i] - buy2);
// 在第二次买卖的基础上取最大利润
buy3 = Math.min(buy3, prices[i] - sell2);
sell3 = Math.max(sell3, prices[i] - buy3);;
}
return sell3;
}
}
面试高频TOP202 文章被收录于专栏
面试高频TOP202题解