Advertisement
Guest User

Untitled

a guest
Aug 20th, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. public class StockSingleSellDandC {
  2.  
  3. public Result maxProfit(int [] prices, int start, int end){
  4. if(start>=end){
  5. return new Result(0,0,0);
  6. }
  7. int mid = start + (end-start)/2;
  8. Result leftResult = maxProfit(prices,start,mid);
  9. Result rightResult = maxProfit(prices,mid+1,end);
  10. int minLeftIndex = getMinIndex(prices, start, mid);
  11. int maxRightIndex = getMaxIndex(prices, mid, end);
  12. int centerProfit = prices[maxRightIndex] - prices[minLeftIndex];
  13. if(centerProfit>leftResult.profit && centerProfit>rightResult.profit){
  14. return new Result(centerProfit,minLeftIndex,maxRightIndex);
  15. }else if(leftResult.profit>centerProfit && rightResult.profit>centerProfit){
  16. return leftResult;
  17. }else{
  18. return rightResult;
  19. }
  20. }
  21.  
  22. public int getMinIndex(int [] A, int i, int j){
  23. int min = i;
  24. for (int k = i+1; k <=j ; k++) {
  25. if(A[k]<A[min])
  26. min = k;
  27. }
  28. return min;
  29. }
  30. public int getMaxIndex(int [] A, int i, int j){
  31. int max = i;
  32. for (int k = i+1; k <=j ; k++) {
  33. if(A[k]>A[max])
  34. max = k;
  35. }
  36. return max;
  37. }
  38.  
  39. public static void main(String[] args) {
  40. StockSingleSellDandC m = new StockSingleSellDandC();
  41. int [] prices = { 200, 500, 1000, 700, 30, 400, 900, 400, 50};
  42. int start = 0;
  43. int end = prices.length-1;
  44. Result result = m.maxProfit(prices,start,end);
  45. System.out.println("Maximum Profit(Divide & Conquer): " +result.profit + ", buy date index: " + result.buyDateIndex +
  46. ", sell date index: " + result.sellDateIndex);
  47. }
  48. }
  49. class Result{
  50. int profit=0;
  51. int buyDateIndex=0;
  52. int sellDateIndex=0;
  53. public Result(int profit, int buyDateIndex, int sellDateIndex){
  54. this.profit = profit;
  55. this.buyDateIndex = buyDateIndex;
  56. this.sellDateIndex = sellDateIndex;
  57. }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement