Created
March 9, 2013 07:23
-
-
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.
This file contains hidden or 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). | |
| */ | |
| 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; | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not working for the large set.