import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 计算最大收益
     * @param prices int整型一维数组 股票每一天的价格
     * @return int整型
     */
    //[8,9,2,5,4,7,1]
    public int maxProfit (int[] prices) {
        if(prices == null || prices.length < 2) return 0 ;
        int len = prices.length ;
        //f[i]为前i天的最大利益
        int f[] = new int[len +1] ;
        f[0] = 0 ;
        f[1] = 0 ;
        for(int i = 2 ; i <= len ; i ++) {
            if(prices[i-1] < prices[i-2]) {
                f[i] = f[i-1] ;
            } else {
               int j = i - 3 ;
               while(j >= 0) {
                   if(prices[j] < prices[j+1]) {
                       j -- ;
                   } else {
                       f[i] = f[j+1] + prices[i-1] - prices[j+1] ;
                       break ;
                   }
               }
                if(j < 0) {
                    f[i] = prices[i-1] - prices[0] ;
                }
            }
        }
        return f[len] ;
    }
}