Best Time to Buy and Stock, sellstock

Source: Internet
Author: User

Best Time to Buy and Stock, sellstock

This article is in the study of the summary, welcome to reprint but please note the Source: http://blog.csdn.net/pistolove/article/details/43024967


Say you have an array for which the ith element is the price of a given stock on day I.

If you were only permitted to complete at most one transaction (ie, buy one and every one share of the stock), design an algorithm to find the maximum profit.


Ideas:

(1) The question is to give an array. The value of element I in the array corresponds to the stock on the day I. Please only make one transaction, that is, buy and sell once, the maximum profit.

(2) This question examines the maximum difference. For this question, if the value of day I is greater than the value of day I + 1, you will not be able to buy it if it is monotonic decreasing. Only the value of day I is less than the value of day I + 1, purchase can be profitable only when it is monotonically increasing. Therefore, traverse the array to compare the difference between adjacent elements, and obtain the maximum profit.

(3) I hope this article will help you.


The algorithm code is implemented as follows:

/** * @authod liqq */public int maxProfit(int[] prices) {int len = prices.length;if (prices == null || len <= 1)return 0;int curr = prices[0];int profit = 0;for (int i = 0; i < len; i++) {int nex = prices[i];profit = nex - curr > profit ? nex - curr : profit;curr = curr < nex ? curr : nex;}return profit;}



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.