買股票的最佳時期

買股票的最佳時期

與求最大子序列和做法一樣,直接使用動態規劃
時間複雜度爲O(n)

 public int maxProfit(int[] prices) {
        int []a=new int[prices.length];
        int s=0,max=0;
        for(int i=0;i<prices.length-1;i++){
            a[i]=prices[i+1]-prices[i];
        }
        for(int j=0;j<prices.length-1;j++){
            s+=a[j];
            if(s>max){
                max=s;
                //System.out.print(max+" ");
            }else if(s<0){
                s=0;
            }
        }
       return max;
    }


發佈了39 篇原創文章 · 獲贊 31 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章