Created
July 10, 2014 05:53
-
-
Save Ray1988/c45147aa1aae613c54db to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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<=1){ | |
return 0; | |
} | |
// used to record max profit can get until each day | |
int[] maxProfit=new int[prices.length]; | |
maxProfit[0]=0; | |
for (int i=1; i<prices.length; i++){ | |
if (prices[i]>prices[i-1]){ | |
// price go up, max profit is max profit get by yesterday plus new profit | |
maxProfit[i]=prices[i]-prices[i-1]+maxProfit[i-1]; | |
} | |
else{ | |
// price go down, max profit can get by today should be equal to yesterday. | |
maxProfit[i]=maxProfit[i-1]; | |
} | |
} | |
return maxProfit[maxProfit.length-1]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment