风口的猪-中国牛市

来源:互联网 发布:js面向对象和面向过程 编辑:程序博客网 时间:2024/04/29 00:04

风口之下,猪都能飞。当今中国股市牛市,真可谓“错过等七年”。 给你一个回顾历史的机会,已知一支股票连续n天的价格走势,以长度为n的整数数组表示,数组中第i个元素(prices[i])代表该股票第i天的股价。 假设你一开始没有股票,但有至多两次买入1股而后卖出1股的机会,并且买入前一定要先保证手上没有股票。若两次交易机会都放弃,收益为0。 设计算法,计算你能获得的最大收益。 输入数值范围:2<=n<=100,0<=prices[i]<=100

输入例子:
3,8,5,1,7,8

输出例子:
12

public class Solution {    /**     * 计算你能获得的最大收益     *      * @param prices Prices[i]即第i天的股价     * @return 整型     */    public int calculateMax(int[] prices) {        int max = 0;        int len = prices.length;        for(int i=1; i<len; i++) {            int temp = getMax(prices, 0, i) + getMax(prices, i+1, len-1);            if(temp > max)                max = temp;        }        return max;    }    public int getMax(int[] prices, int start, int end) {        int maxProfit = 0;        int minValue = Integer.MAX_VALUE;        for(int i=start; i<=end; i++) {            if(prices[i] - minValue > maxProfit)                maxProfit = Math.max(prices[i] - minValue, maxProfit);            if(minValue > prices[i])                minValue = prices[i];        }        return maxProfit;    }}

DP动态规划的升级版,可以买两次就拆分为两个一次

0 0