[Leetcode click Notes] best time to buy and buy stock III

Source: Internet
Author: User

Say you have an array for whichITh element is the price of a given stock on dayI.

Design an algorithm to find the maximum profit. You may complete at mostTwoTransactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must encrypt the stock before you buy again ).

 

Problem: DP

Scan the array from the past to the next, and use lefttoright [I] to record (0, I) to get the maximum profit;

Scan the array from the back and forth, and use righttoleft [I] to record (I, n-1) the maximum profit;

The final maximum profit is max (lefttoright [I] + righttoleft [I]).

For example, if prices = {1, 2, 3, 2, 5, 7 },

Lefttoright = {0, 1, 2, 4, 6}

Righttoleft = {6, 5, 5, 2, 0}

The final maximum profit is 2 + 5 = 7. Indicates that ~ 2 (or 0 ~ 3) the profit is 2 in this range, and 2 ~ 5 (or 3 ~ 5) profit is 5 in this range, and the final profit is 7.

The Code is as follows:

 1 public class Solution { 2     public int maxProfit(int[] prices) { 3         if(prices == null || prices.length == 0) 4             return 0; 5          6         int[] LeftToRight = new int[prices.length]; 7         int[] RightToLeft = new int[prices.length]; 8          9         int minimal = prices[0];10         LeftToRight[0] = 0;11         for(int i = 1;i < prices.length;i++){12             minimal = Math.min(minimal, prices[i]);13             LeftToRight[i] = Math.max(LeftToRight[i-1], prices[i]-minimal);14         }15         16         int profit = 0;17         //From Right to left18         RightToLeft[prices.length-1] = 0;19         int maximal = prices[prices.length-1];20         for(int i = prices.length-2;i >= 0;i--){21             maximal = Math.max(prices[i], maximal);22             RightToLeft[i]= Math.max(RightToLeft[i+1], maximal-prices[i]);23             profit = Math.max(profit, LeftToRight[i] + RightToLeft[i] );24         }25         26         return Math.max(profit, LeftToRight[0]+RightToLeft[0]);27     }28 }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.