Algorithm-stock trading day

Source: Internet
Author: User
Tags arrays
Title Description

This is the American Regiment's 2016 recruitment of pen questions.


Title Description


In the trading day of the stock market, it is assumed that a maximum of two transactions can be made (that is, the number of purchases and sales is less than or equal to 2), and the rule is that a deal must be executed after another (i.e. buy-sell-buy-sell order). Given the stock change sequence of the day, write a program that calculates the maximum benefits that can be gained in a day. Please use the method of low practice complexity to implement.

Given the price sequence prices and its length n, return the maximum benefit. Guaranteed length is less than or equal to 500.

Test examples:

[10,22,5,75,65,80],6

Return:

87


Algorithmic Thinking


If it is a trade once, that is, the first to buy and then sell, it will be relatively simple to consider:

Stocks at the lowest point to buy, the highest selling must be the most profitable, but there is a time series problem, the difference is the biggest buy sell point is not necessarily the lowest and highest point of the stock price.

For example:

If the price sequence is 10 20 30 5, then the maximum profit is 20, 10 buy, 30 sell, the minimum price is 5, not the minimum point to buy

If the price sequence is 10 20 30 5 28, then the maximum profit is 20, 5 buy, 28 sell, the maximum point price is 30, not the maximum point to sell

30 10 28 5 20, the maximum profit is 18, 10 buy, 28 sell, the maximum point is 30, the minimum price is 5, not the minimum point to buy or sell at the maximum point.


The goal is: The price below subtracts the maximum value of the difference between the preceding price.

Algorithm: All the following prices minus the previous price of the case are listed, find a maximum, exhausted all conditions, must be able to find solutions.


Now it adds difficulty, two trades, every time must buy after sale.

It looks like the loop has added one more dimension. And to control the first sale after the second time to buy.


Brainwave thought of a way to split the price sequence into one.

Two trades are performed in two separate sequences, finding the respective maximum value plus total.

Sequence splitting, to ensure that each sequence has a price greater than two, make sure you can buy or sell

Based on this, if it is three times, four times can also be promoted in turn.


Java Implementation Code


The following is the code that I use Java to implement, for reference only:

/** * @Title: Stock.java * @Package com.oscar999.algorithm * @Description: TODO * @author oscar999 * @date Feb 26, 20

1:44:57 PM * @version V1.0 * * Package com.oscar999.algorithm;
Import java.util.ArrayList;
Import Java.util.Arrays;
Import Java.util.HashMap;
Import java.util.List;

Import Java.util.Map;
     /** * @ClassName: Stock * @Description: TODO * @author oscar999 */public class Stock {/** * @Title: Main * @Description: TODO * @param args */public static void main (string[] args) {List<integer
        > pricelist = new arraylist<integer> (Arrays.aslist (10, 22, 5, 75, 65, 80));
        Stock stock = new stock ();
        list<map<string, integer>> list = Stock.getmaxprofixinfo (pricelist);
            if (list = null && list.size () > 0) {int maxprofit = 0;
                for (int i = 0; i < list.size (); i++) {map<string, integer> Map = List.get (i); if (MAP.GET ("profit") = null) {int iprofit = integer.valueof (map.get ("profit"));
                        if (Iprofit > 0) {maxprofit + = Iprofit;
                        int ibuy = integer.valueof (Map.get ("buy"));
                        int isale = integer.valueof (map.get ("Sale")); System.out.println ("buy:position=" + (ibuy + 1) + ";
                        Price= "+ pricelist.get (ibuy)); System.out.println ("sale:position=" + (Isale + 1) + ";
                    Price= "+ pricelist.get (Isale));
        }}} System.out.println ("Max profit=" + maxprofit);
        } else {System.out.println ("There is some error, can ' t get max profit.please check."); }}/** * Divice separate price to the list, get each max, and then Count * * @Title: Getmaxprof Ixinfo * @Description: TODO * @param fprices * @return */Private LIST&LT;MAP&LT;STRING, integer>> getmaxprofixinfo (list<integer> pricelist) {list<map<string, Integer>> List
        = new arraylist<map<string, integer>> ();
        int ilength = Pricelist.size ();
        int maxprofit = 0;
        map<string, integer> sub1maxinfofinal = null;
        map<string, integer> sub2maxinfofinal = null; for (int isep = 2; isep < iLength-2; isep++) {list<integer> sub1pricelist = pricelist.sublist (0, I
            SEP);
            list<integer> sub2pricelist = pricelist.sublist (isep, ilength);
            map<string, integer> sub1maxinfo = getmaxprofixinfobyprices (sub1pricelist, 0);
            map<string, integer> sub2maxinfo = Getmaxprofixinfobyprices (sub2pricelist, ISEP);
            int subprofit = 0;
            int sub1profit = integer.valueof (sub1maxinfo.get ("profit"));
            int sub2profit = integer.valueof (sub2maxinfo.get ("profit"));
        if (Sub1profit > 0) {        Subprofit + = Sub1profit;
            } if (Sub2profit > 0) {subprofit + = Sub2profit;
                } if (Subprofit > Maxprofit) {maxprofit = Subprofit;
                if (Sub1profit > 0) {sub1maxinfofinal = Sub1maxinfo;
                } else {sub1maxinfofinal = null;
                } if (Sub2profit > 0) {sub2maxinfofinal = Sub2maxinfo;
                } else {sub2maxinfofinal = null;
        }}} if (sub1maxinfofinal! = null) {List.add (sub1maxinfofinal);
        } if (sub2maxinfofinal! = null) {List.add (sub2maxinfofinal);
    } return list;  }/** * * @Title: Getmaxprofixinfobyprices * @Description: TODO * @param pricelist * @param
 Ibaseposition *, sub list postion should add.    * @return */private map<string, integer> getmaxprofixinfobyprices (list<integer> pricelist, int i
        baseposition) {map<string, integer> Map = null;
            if (pricelist! = null && pricelist.size () > 1) {int ilength = Pricelist.size ();
            Integer maxprofit = 0;
            int iBuy = 0;
            int iSale = 0; for (int i = 0, i < ilength; i++) {for (int j = i + 1; j < Ilength; J + +) {Inte
                    Ger Profit = Pricelist.get (j)-Pricelist.get (i);
                        if (Profit > Maxprofit) {maxprofit = profit;
                        IBuy = i;
                    ISale = j;  }}} if (Maxprofit > 0 && iSale > IBuy) {map = new
                Hashmap<string, integer> ();
                Map.put ("buy", IBuy + ibaseposition); Map.put ("Sale", ISale+ ibaseposition);
            Map.put ("Profit", Maxprofit);
    }} return map; }

}


Message
Finally, welcome to a better algorithm or solution of the fellow elegance

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.