剑指offer面试题63(java版) 题目:
假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该股票一次可能获得的最大利润是多少?

只允许 一次交易

 /**
     * 只允许 一次交易
     * @param prices
     * @return
     */
    public int maxProfit(int[] prices){
        int rs=0;
        int min=Integer.MAX_VALUE;
        for(int p:prices ){
            min=Math.min(min,p);
            rs=Math.max(rs,p-min);
        }
        return rs;
    }

可以多次交易

可以把价格数组想象成带时间的曲线,只要抓住每次上升阶段的最高点和最低点,然后把差相加就是最大收益。

在这里插入图片描述

/**
     * 可以多次交易
     * @param prices
     * @return
     */
    public int maxProfit2(int[] prices){
        int rs=0;
        int min=Integer.MAX_VALUE;
        for(int i=prices.length-1;i>0; ){
            int head=i-1;
            while(head>0&&prices[head]<prices[head+1]&&prices[head]>prices[head-1]){
                head--;
            };
            if(head>=0){
                int diff=prices[i]-prices[head];
                if(diff>0){
                    rs+=diff;
                }
            }
            i=head;
        }
        return rs;
    }

测试测试

 public static void main(String[] args) {
        ProfitDemo profitDemo=new ProfitDemo();
        int[] prices={20,40,90,50,10,60};
        System.out.println("一次交易最大收益:"+profitDemo.maxProfit(prices));
        System.out.println("多次交易最大收益:"+profitDemo.maxProfit2(prices));
    }

在这里插入图片描述

关注公众号,可以获取学习资料和源码
在这里插入图片描述

Logo

加入社区!打开量化的大门,首批课程上线啦!

更多推荐