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

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

假設你有一個數組,數組中第i個元素是給定股票在第i天的價格。

設計一個算法來得到最大利潤。交易的次數沒有限制(可買入再賣出多次)。但是,不能同時參與超過一次交易(再次買入之前需把現有股票賣出)。

代碼參考了discuss中的高票答案,是我自己想復雜了,一直想找到何時買入何時賣出,其實並不需要

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

return max;
}
}

122. Best Time to Buy and Sell Stock II