Leetcode notes: Best time to Buy and Sell Stock III

Source: Internet
Author: User

I. Title Description

Say you had an array for which the i-th element was the price of a given stock on day I.

Design an algorithm to find the maximum profit. You are in most of the transactions.

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

Two. Topic analysis

Compared with the first two questions, this problem limits the number of trades traded, up to two trades.

You can use dynamic planning to do it, first of all, first scan, calculate [0, …, i] the maximum profit in the sequence, profit save it with an array f1 , this step is the complexity of O(n) time.

The second step is to reverse scan, calculate [i, …, n - 1] the maximum profit in the sub-sequence, profit also save it with an array f2 , the time complexity of this step is also O(n) .

The last step, for, yes f1 + f2 , find the maximum value.

Three. Sample code

#include <iostream>#include <vector>using namespace STD;classSolution { Public:intMaxprofit ( vector<int>&prices) {intSize = Prices.size ();if(Size <=1)return 0; vector<int>F1 (size); vector<int>F2 (size);intMINV = prices[0]; for(inti =1; i < size; ++i) {MINV =STD:: Min (MINV, prices[i]); F1[i] =STD:: Max (F1[i-1], Prices[i]-MINV); }intMAXV = Prices[size-1]; F2[size-1] =0; for(inti = size-2; I >=0; -i) {MAXV =STD:: Max (MAXV, prices[i]); F2[i] =STD:: Max (F2[i +1], maxv-prices[i]); }intsum =0; for(inti =0; i < size; ++i) sum =STD:: Max (SUM, f1[i] + f2[i]);returnSum }};

Four. Summary

Compared to the first two questions, the problem is slightly more difficult, and the question related to the topic there are several. Subsequent updates ...

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Leetcode notes: Best time to Buy and Sell Stock III

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.