[Leetcode 122, Medium] Best Time to Buy and Sell Stock II

Problem:

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).

Analysis:


Solutions:

C++:

    int maxProfit(vector<int>& prices) 
    {
	    int maxValue = 0;
	    vector<int> v_profits;
	    v_profits.push_back(0);
	    int max_profit = 0;
	    for(int i = 1; i < prices.size(); ++i)
		    v_profits.push_back(prices[i] - prices[i - 1]);

	    for(int i = 0; i < v_profits.size(); ++i)
		    max_profit += (v_profits[i] > 0 ? v_profits[i] : 0);

	    return max_profit;
    }
Java:


Python:

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