p64 涓嶉檺娆℃暟杩涜鑲$エ涔板崠鐨勬渶澶у埄娑?(leetcode 122)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了p64 涓嶉檺娆℃暟杩涜鑲$エ涔板崠鐨勬渶澶у埄娑?(leetcode 122)相关的知识,希望对你有一定的参考价值。

鏍囩锛?a href='http://www.mamicode.com/so/1/%e8%a7%a3%e9%a2%98%e6%80%9d%e8%b7%af' title='瑙i鎬濊矾'>瑙i鎬濊矾   leetcode   public   sel   tco   pac   +=   int   span   

涓€锛氳В棰樻€濊矾

鏂规硶涓€锛氫笉鏂殑瀵绘壘鑲$エ鐨勬渶灏忓€煎拰鏈€澶у€硷紝骞跺湪鏈€灏忓€煎緱鏃跺€欎拱鍏ワ紝鍦ㄦ渶澶у€煎緱鏃跺€欏崠鍑恒€俆ime:O(n),Space:O(1)

鏂规硶浜岋細璐績娉曪紝鍙鍚庝竴澶╃殑鍊煎ぇ浜庡墠涓€澶╃殑鍊硷紝閭d箞灏辫繘琛屼拱鍗栥€俆ime:O(n),Space:O(n)

浜岋細瀹屾暣浠g爜绀轰緥 (C++鐗堝拰Java鐗?

鏂规硶涓€C++锛?/p>

class Solution {
public:
    int maxProfit(vector<int>& prices) 
    {
        if (prices.size() == 0) return 0;
        int n = prices.size();
        int i = 0, buy = 0, sell = 0,maxProfit=0;

        while (i < n - 1)
        {
            while (i < n - 1 && prices[i + 1] <= prices[i]) i++;
            buy = prices[i];
            while (i < n - 1 && prices[i + 1] >= prices[i]) i++;
            sell = prices[i];

            maxProfit += (sell-buy);
        }

        return maxProfit;
    }
};

鏂规硶涓€Java锛?/p>

class Solution {
    public int maxProfit(int[] prices)
    {
           if(prices==null||prices.length==0) return 0;
           int maxProfit=0,i=0,buy=0,sell=0;
           int n=prices.length;
           
           while(i<n-1)
           {
               while(i<n-1 && prices[i+1]<=prices[i]) i++;
               buy=prices[i];
               while(i<n-1 && prices[i+1]>=prices[i]) i++;
               sell=prices[i];
               
               maxProfit+=(sell-buy);
           }
           
           return maxProfit;
    }
}

鏂规硶浜孋++:

class Solution {
public:
    int maxProfit(vector<int>& prices) 
    {
        if (prices.size() == 0) return 0;
        int maxProfit=0;

        for (int i = 1; i < prices.size(); i++)
        {
            if (prices[i] > prices[i - 1])
                maxProfit += (prices[i]-prices[i-1]);
        }

        return maxProfit;
    }
};

鏂规硶浜孞ava:

class Solution {
    public int maxProfit(int[] prices)
    {
           if(prices==null||prices.length==0) return 0;
           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;
    }
}

 

以上是关于p64 涓嶉檺娆℃暟杩涜鑲$エ涔板崠鐨勬渶澶у埄娑?(leetcode 122)的主要内容,如果未能解决你的问题,请参考以下文章

鏈哄櫒鍒嗛厤

鍒嗗竷寮忎簨鍔′箣濡備綍鍩轰簬RocketMQ鐨勪簨鍔℃秷鎭壒鎬у疄鐜板垎甯冨紡绯荤粺鐨勬渶缁堜竴鑷存€э紵

MySQL瀛樺偍娴烽噺鏁版嵁鐨勬渶鍚庝竴鎷涳細鍒嗗簱鍒嗚〃

36涓伐浣滀腑甯哥敤鐨凧avaScript鍑芥暟鐗囨