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 at most two transactions.Note:You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).Subscribe to see which companies asked this question.
题意:股票的买入卖出。你只有两次机会买入卖出。
public class Solution { public int maxProfit(int[] prices) { if(prices==null || prices.length<2)return 0; //O(n^2)哎 int sum=0; for(int i=1;isum)sum=temp; } return sum; } public static int getMax(int[] prices,int left,int right){ if(left>=prices.length)return 0; int Min=prices[left]; int sum=0; for(int i=left+1;i<=right;i++){ Min=Math.min(Min,prices[i]); sum=Math.max(sum,prices[i]-Min); } System.out.println(sum); return sum; // } // //first[i]从左往右遍历,表示到第i天时卖出能赚到的最大钱 // int[] first=new int[prices.length]; // //second[i]从右往左遍历,表示从第i天到最后一天能赚到的最大钱。本质还是分两部分计算。只不过是分开两次扫描数组 // int[] second=new int[prices.length]; // int min=prices[0]; // for(int i=1;i =0;i--){ // max=Math.max(max,prices[i]); // second[i]=Math.max(second[i+1],max-prices[i]); // } // int ret=0; // for(int i=0;i
PS:解法一是直接以第i天为界,求两边的最大收益。但是需要O(N^2)。
优化:用俩数组,遍历两次。