Stock market problem (the stock markets problem)

Source: Internet
Author: User

Question: Let us suppose we had an array whose ith element gives the price of a share on the day I.
If you were only permitted to buy one share of the stock and sell one share of the stock, design a algorithm to find the Best times to buy and sell.

Ask for the best time to buy and sell, which is the point of maximizing profits. A profit is generated when the stock price is less than the stock price at the time of the sale.

At first glance, we might think of finding the minimum and maximum points of the array, but the buy must be before the sale.

The problem is equivalent to:

Find I and J that maximizes Aj–ai, where I < J.

The simple method is to calculate all the possibilities, in the comparison maximum, the time required is O (N2), perhaps we can solve in O (n) time.

To solve this problem, you need to trace the minimum value

Updates the index of the minimum value while traversing

Compare the difference between the current value and the minimum value

Time duration Update Max difference

Algorithm implementation.

#include <stdio.h>voidGetbesttime (intStocks[],intsize) {    intbuy =0, sell =0; intMin =0; inti; intMaxDiff =0; Buy= Sell =0;  for(i =0; i < size; i++)    {        if(Stocks[i] <stocks[min]) min=i; intdiff = stocks[i]-Stocks[min]; if(diff >MaxDiff) {Buy=min; Sell=i; MaxDiff=diff; }} printf ("\nthe day to buy is-%d at price%d", Buy, stocks[buy]); printf ("\nthe day to sell is-%d at price%d", Sell, Stocks[sell]);} intMainvoid){    intStocks[] = {3,6,Ten,2, the, +,1, at}; intbuy =0; intSell =0; Getbesttime (Stocks,8); return 0;}

Stock market problem (the stock markets problem)

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.