最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C++實現(xiàn)LeetCode(122.買股票的最佳時間之二)

 更新時間:2021年07月26日 15:19:31   作者:Grandyang  
這篇文章主要介紹了C++實現(xiàn)LeetCode(122.買股票的最佳時間之二),本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下

[LeetCode] 122.Best Time to Buy and Sell Stock II 買股票的最佳時間之二

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

這道跟之前那道Best Time to Buy and Sell Stock 買賣股票的最佳時間很類似,但都比較容易解答。這道題由于可以無限次買入和賣出。我們都知道炒股想掙錢當(dāng)然是低價買入高價拋出,那么這里我們只需要從第二天開始,如果當(dāng)前價格比之前價格高,則把差值加入利潤中,因為我們可以昨天買入,今日賣出,若明日價更高的話,還可以今日買入,明日再拋出。以此類推,遍歷完整個數(shù)組后即可求得最大利潤。代碼如下:

C++ 解法:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int res = 0, n = prices.size();
        for (int i = 0; i < n - 1; ++i) {
            if (prices[i] < prices[i + 1]) {
                res += prices[i + 1] - prices[i];
            }
        }
        return res;
    }
};

Java 解法:

public class Solution {
    public int maxProfit(int[] prices) {
        int res = 0;
        for (int i = 0; i < prices.length - 1; ++i) {
            if (prices[i] < prices[i + 1]) {
                res += prices[i + 1] - prices[i];
            }
        }
        return res;
    }
}

類似題目:

Best Time to Buy and Sell Stock with Cooldown

Best Time to Buy and Sell Stock IV

Best Time to Buy and Sell Stock III

Best Time to Buy and Sell Stock

到此這篇關(guān)于C++實現(xiàn)LeetCode(122.買股票的最佳時間之二)的文章就介紹到這了,更多相關(guān)C++實現(xiàn)買股票的最佳時間之二內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

平南县| 日照市| 岱山县| 武汉市| 新乡县| 甘南县| 郁南县| 衡阳市| 盐津县| 诸城市| 玉树县| 连云港市| 绥棱县| 罗甸县| 淮安市| 东源县| 威宁| 静海县| 抚宁县| 太仓市| 杭锦后旗| 开化县| 北票市| 静乐县| 延庆县| 达孜县| 巫溪县| 南江县| 竹溪县| 全南县| 巴东县| 铜陵市| 郎溪县| 师宗县| 杭州市| 西充县| 天全县| 泰来县| 新邵县| 如东县| 遂宁市|