1. 程式人生 > >[LeetCode] Best Time to Buy and Sell Stock II 買股票的最佳時間之二

[LeetCode] 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 買賣股票的最佳時間很類似,但都比較容易解答。這道題由於可以無限次買入和賣出。我們都知道炒股想掙錢當然是低價買入高價丟擲,那麼這裡我們只需要從第二天開始,如果當前價格比之前價格高,則把差值加入利潤中,因為我們可以昨天買入,今日賣出,若明日價更高的話,還可以今日買入,明日再丟擲。以此類推,遍歷完整個陣列後即可求得最大利潤。程式碼如下:

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; } }

類似題目: