java 买卖股票的最佳时机

//买卖股票的最佳时机 II
public class Stock
{
    // 方法1
    public static int calculate(int prices[], int s)
    {
        if (s >= prices.length)
            return 0;
        int max = 0;
        for (int start = s; start < prices.length; start++)
        {
            int maxprofit = 0;
            for (int i = start + 1; i < prices.length; i++)
            {
                if (prices[start] < prices[i])
                {
                    int profit = calculate(prices, i + 1) + prices[i]
                            - prices[start];
                    if (profit > maxprofit)
                        maxprofit = profit;
                }
            }
            if (maxprofit > max)
                max = maxprofit;
        }
        return max;
    }

    public static int maxProfit1(int[] prices)
    {
        return calculate(prices, 0);
    }

    // 方法2——简单
    public static int maxProfit2(int[] prices)
    {
        int maxprofit = 0;
        for (int i = 1; i < prices.length; i++)
        {
            if (prices[i] > prices[i - 1])
                maxprofit += prices[i] - prices[i - 1];
        }
        return maxprofit;
    }

    // 方法3
    public static int maxProfit4(int[] prices)
    {
        int i = 0;
        int valley = prices[0];
        int peak = prices[0];
        int maxprofit = 0;
    
        while (i < prices.length - 1)
        {
            // 股票下跌,当前值大于下一个值,说明股票在下降,当前i不大于下一个值i+1的时候,i买入最小值
            while (i < prices.length - 1 && prices[i] >= prices[i + 1])
            {
                i++;
            }
            valley = prices[i]; // 股票最小值买入
            // 股票上涨的最大值,当前值i小于下一个值i+1,说明股票在上涨,当i大于i+1的时候,i卖出最大值
            while (i < prices.length - 1 && prices[i] <= prices[i + 1])
            {
                i++;
            }
            peak = prices[i];// 股票上涨的最大值卖出
            maxprofit += peak - valley;
        }
        return maxprofit;
    }

    public static void main(String[] args)
    {
        int[] prices =   { 7, 1, 5, 3, 6, 4 };
        int[] prices1 =    { 1, 2, 3, 4, 5 };
        int[] prices2 =     { 7, 6, 4, 3, 1 };
        int[] prices3 =  { 7, 6, 8, 3, 5, 6, 1 };
        // System.out.println(maxProfit2(prices));
        // System.out.println(maxProfit2(prices1));
        // System.out.println(maxProfit2(prices2));
        System.out.println(maxProfit4(prices3));
    }
}
 

 

// 方法2  简单处理

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值