1. 程式人生 > >LeetCode -- Best Time to Buy and Sell Stock II

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 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 Solution {
    public int MaxProfit(int[] prices) {
        if(prices == null || prices.Length == 0){
		return 0;
	}
	
	var sum = 0;
	for(var i = 0; i < prices.Length - 1; i ++){
		sum += prices[i] < prices[i+1] ? prices[i+1]-prices[i] : 0;
	}
	
	return sum;
    }
}


LeetCode -- Best Time to Buy and Sell Stock II