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)