# Leetcode -- best time to buy and keep stock

Source: Internet
Author: User

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.

Question: Suppose you have an array where the I element represents the given I-day stock price.

If you are allowed to complete at most one transaction (for example, buy and sell one stock), design an algorithm to find the maximum profit.

The most naive solution is to traverse all the backend and locate the minimum value. Timeout.

`public static int maxProfit(int[] prices){int len = prices.length;if(len <= 1)return 0;int max = 0;for(int i=0;i<len;i++){for(int j=i+1;j<len;j++){int profit = prices[j] - prices[i];if(max < profit)max = profit;}}return max;}`

The following method is much easier. First, assign the value of the first element to the minimum, and calculate the profit in turn. Each time you compare it with the maximum value, and save the new maximum value and the new minimum value.

`public static int maxProfit(int[] prices){int len = prices.length;if(len <= 1)return 0;int min = prices[0],max = 0;for(int i=1;i<len;i++){int profit = prices[i] - min;if(max < profit)max = profit;if(min > prices[i])min = prices[i];}return max;} `

Related Keywords:

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.