Skip to content

Instantly share code, notes, and snippets.

@Ray1988
Created July 10, 2014 05:53
Show Gist options
  • Save Ray1988/c45147aa1aae613c54db to your computer and use it in GitHub Desktop.
Save Ray1988/c45147aa1aae613c54db to your computer and use it in GitHub Desktop.
/*
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