Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Last active December 12, 2015 02:38
Show Gist options
  • Save charlespunk/4700451 to your computer and use it in GitHub Desktop.
Save charlespunk/4700451 to your computer and use it in GitHub Desktop.
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 Solution {
public int maxProfit(int[] prices) {
// Start typing your Java solution below
// DO NOT write main() function
if(prices == null || prices.length == 0) return 0;
int hold = 0;
boolean have = false;
int earn = 0;
for(int i = 0; i < prices.length - 1; i++){
int money = prices[i + 1] - prices[i];
if(money > 0){
if(!have){
hold = prices[i];
have = true;
}
}
else if(money < 0){
if(have){
earn += prices[i] - hold;
have = false;
}
}
}
if(have) earn += prices[prices.length - 1] - hold;
return earn;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment