Skip to content

Instantly share code, notes, and snippets.

@daifu
Created March 9, 2013 07:23
Show Gist options
  • Select an option

  • Save daifu/5123303 to your computer and use it in GitHub Desktop.

Select an option

Save daifu/5123303 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.
/*
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).
*/
import java.util.*;
public class Solution {
Hashtable<Integer, Boolean> seen = new Hashtable<Integer, Boolean>();
public int maxProfit(int[] prices) {
// Start typing your Java solution below
// DO NOT write main() function
int size = prices.length;
int max_price = 0;
for(int i = 0; i < size; i++) {
seen.clear();
int price = getPrice(prices, i, size);
if(price > max_price) {
max_price = price;
}
}
return max_price;
}
public int getPrice(int[] prices, int start, int end) {
int total_price = 0;
int first = prices[start];
for(int i = start + 1; i < end; i++) {
if(seen.containsKey(i)) continue;
if(prices[i] > first) {
total_price += (prices[i] - first);
}
total_price += getPrice(prices, i, end);
seen.put(i, true);
}
return total_price;
}
}
@daifu

daifu commented Mar 9, 2013

Copy link
Copy Markdown
Author

Not working for the large set.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment