题解 | #牛群买卖策略优化#
牛群买卖策略优化
https://www.nowcoder.com/practice/c8514318443a48218efde630ae11b4c3
知识点:贪心
思路:与上一题的一个区别就是,上一题找数组最大值(同时记录一个在此之前的最小值)
这题则是找数组中每一个最大连续升序列,对应这些序列,我都可以操作买入卖出,狠狠赚一笔
编程语言:java
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param prices int整型一维数组 * @return int整型 */ public int max_profitv2 (int[] prices) { // write code here int max = prices[0]; int min = prices[0]; int sum = 0; for (int i = 1; i < prices.length; i++) { if (max > prices[i]) { //找到一个升序列后,全部更新,重头再来,狠狠赚一笔 sum += max - min; min = prices[i]; max = prices[i]; } else //更新升序列最大值 max = prices[i]; } //如果整个是升序列 sum +=max -min; return sum; } }