Leetcode -- best time to buy and stock Stock III

Source: Internet
Author: User

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 encrypt the stock before you buy again ).

Original question link: https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/

Question: Suppose you have an array where the I element represents the given I-day stock price.

Design an algorithm to find the maximum profit. You can complete up to two transactions.

Idea: divide the array into two intervals and obtain the maximum difference between these two intervals.

I learned from the practices of Netizens [1]. Dynamic Planning: records the status with two arrays. f [I] indicates the maximum profit of the range [0, I] (0 <= I <= N-1, G [I] indicates the maximum profit of the range [I, n-1] (0 <= I <= N-1.

public static int maxProfit(int[] prices) {if (prices.length < 2)return 0;int f[] = new int[prices.length];int g[] = new int[prices.length];for (int i = 1, valley = prices[0]; i < prices.length; ++i) {valley = Math.min(valley, prices[i]);f[i] = Math.max(f[i - 1], prices[i] - valley);}for (int i = prices.length - 2, peak = prices[prices.length - 1]; i >= 0; --i) {peak = Math.max(peak, prices[i]);g[i] = Math.max(g[i], peak - prices[i]);}int max_profit = 0;for (int i = 0; i < prices.length; ++i)max_profit = Math.max(max_profit, f[i] + g[i]);return max_profit;}

[1] http://www.cnblogs.com/apoptoxin/p/3770092.html



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.