1. 程式人生 > >Best Time to Buy and Sell Stock II 最佳時間買入賣出股票(多次買賣)@LeetCode

Best Time to Buy and Sell Stock II 最佳時間買入賣出股票(多次買賣)@LeetCode

題目:

最佳時間買入賣出股票:你有一個數組儲存了股票在第i天的價錢,現在你可以進行多次買入賣出,但同一時間你手上只能保持一個股票,如何賺的最多

思路:

貪心法,本題和前面的Best Time to Buy and Sell Stock 不同在於,本題可以多次買賣股票,
從而累積賺取所有的價格差。因此用貪心法,基本思想是鎖定一個低價,然後在價格升到區域性最高點
(即下一天的價錢就下降了)時候,丟擲股票,然後把下一天較低的價錢作為買入,接著計算。
要注意最後要處理最後一次的利潤

package Level3;

/**
 * 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).
 *
 */
public class S122 {

	public static void main(String[] args) {
		int[] prices = {2,1,2,0,4};
		System.out.println(maxProfit(prices));
	}

	// 貪心法,本題和前面的Best Time to Buy and Sell Stock 不同在於,本題可以多次買賣股票,
	// 從而累積賺取所有的價格差。因此用貪心法,基本思想是鎖定一個低價,然後在價格升到區域性最高點
	// (即下一天的價錢就下降了)時候,丟擲股票,然後把下一天較低的價錢作為買入,接著計算。
	// 要注意最後要處理最後一次的利潤
	public static int maxProfit(int[] prices) {
		if(prices.length == 0){
			return 0;
		}
        int totalProfit = 0;
        int startIndex = 0;
        int i;
        
        for(i=1; i<prices.length; i++){
        	if(prices[i] < prices[i-1]){	// 因為第i天的價錢就下降了,因此把從startIndex到i-1的利潤積累到總利潤中
        		totalProfit += prices[i-1] - prices[startIndex];
        		startIndex = i;		// 更新startIndex
        	}
        }
    	// 記得要處理最後一次的利潤
        if(prices[i-1] > prices[startIndex]){
        	totalProfit += prices[i-1] - prices[startIndex];
        }
        
        return totalProfit;
    }
}


Again:

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

其實最簡單的做法是:

計算每個相鄰的diff差,只要diff大於0,就累積起來

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


相關推薦

Best Time to Buy and Sell Stock II 最佳時間買入股票買賣@LeetCode

題目:最佳時間買入賣出股票:你有一個數組儲存了股票在第i天的價錢,現在你可以進行多次買入賣出,但同一時間你手上只能保持一個股票,如何賺的最多思路:貪心法,本題和前面的Best Time to Buy and Sell Stock 不同在於,本題可以多次買賣股票,從而累積賺取所

Best Time to Buy and Sell Stock III 最佳時間買入股票買賣@LeetCode

轉載:https://blog.csdn.net/fightforyourdream/article/details/14503469 題目: 最佳時間買入賣出股票:你有一個數組儲存了股票在第i天的價錢,現在你最多進行兩次買賣,但同一時間你手上只能保持一個股票,如何賺的最多 思路:

Leetcode Best Time to Buy and Sell Stock II

con max and [] python self leet sel ice class Solution: # @param {integer[]} prices # @return {integer} def maxProfit(sel

[LeetCode] 22. Best Time to Buy and Sell Stock II Java

股票 log ive highlight transacti ever 方法 size 可能 題目: Say you have an array for which the ith element is the price of a given stock on day i

[LeetCode] Best Time to Buy and Sell Stock II

array tran toc public ans arr action let turn Say you have an array for which the ith element is the price of a given stock on day i. Des

LeetCode——Best Time to Buy and Sell Stock II

股票 this mil ng- posit ria 時間 tco ++ Say you have an array for which the ith element is the price of a given stock on day i. Desi

[Array]122. Best Time to Buy and Sell Stock IIobscure

nbsp 實現 元素 you max -s script -1 times Say you have an array for which the ith element is the price of a given stock on day i. Design an

leetcode - Best Time to Buy and Sell Stock II

color return align eve like art pro position sign Say you have an array for which the ith element is the price of a given stock on

LeetCode -- Best Time to Buy and Sell Stock II

ice sel return fin ransac ret 難度 stock share 題目描寫敘述:Say you have an array for which the ith element is the price of a given stock on da

【算法分析與設計】【第一周】121.Best Time to Buy and Sell Stock&122. Best Time to Buy and Sell Stock II

部分 簡化 是我 -i 復雜 style 代碼 求一個 時間 原題來自:121:https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/ 122:https://leetcode.c

122.Best Time to Buy and Sell Stock II

pan -i 題解 得到 sel 獲得 open 但是 blog 題目鏈接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/ 題目大意:基本定義與121類似,不同點:1

Leetcode 122: Best Time to Buy and Sell Stock II

com same clas multipl fit sel fin ans let Say you have an array for which the ith element is the price of a given stock on day i. Design

122. Best Time to Buy and Sell Stock II

find 設計 turn 之前 not div multiple ++ 再次 Say you have an array for which the ith element is the price of a given stock on day i. Design a

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

complete design fit sha 一個 tran 利潤 多個 mes Say you have an array for which the ith element is the price of a given stock on day i. Design

白菜刷LeetCode記-122. Best Time to Buy and Sell Stock II

i++ ++ 最大的 lee 技術分享 pre ice 為什麽 @param 今天題目如下: 要求出最大的利益。這題個人不太想得通,看了答案也不太知道為什麽這樣能獲得最大值。代碼如下: 1 /** 2 * @param {number[]} prices 3

Array——LeetCode——Best Time to Buy and Sell Stock II

price time [] turn pan 價格 pri tmp span 【學到的知識點——】 ---------------------------------------------------------------------------------------

LeetCode 122. 買賣股票最佳時機 IIBest Time to Buy and Sell Stock II

必須 toc for pub i++ pre 價格 股票 時機 題目描述 給定一個數組,它的第 i 個元素是一支給定股票第 i 天的價格。 設計一個算法來計算你所能獲取的最大利潤。你可以盡可能地完成更多的交易(多次買賣一支股票)。 註意:你不能同時參與多筆交易(你必須在

LeetCode-122. Best Time to Buy and Sell Stock II

0.原題 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 maximu

LeetCode】116.Best Time to Buy and Sell Stock II

題目描述(Easy) 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

貪心演算法-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 profi