# 121. Best time to Buy and Sell Stock

Source: Internet
Author: User

Update Leetcode to solve Java answers on a regular basis.

Choose from the pick one approach.

Test instructions to allow only one sale, the given array is the price of the item of the day, ask the maximum benefit is how much.

Obviously the best way to get the most benefit is to iterate through the array, and in the process of traversal, the price of each day is read, and it is compared with the minimum value obtained by the preceding traversal, which is the maximum benefit to sell a single time on that day. It is stored and compared with later values in subsequent operations, playable a larger value, and the final result is the maximum possible result for a single transaction.

The code is as follows:

`1  Public classSolution {2      Public intMaxprofit (int[] prices) {3         if(Prices.length = = 0)4             return0;5         intMinprice = Prices[0], max = 0;6          for(inti = 1; i < prices.length; i++){7             if(Prices[i]-minprice >max)8max = Prices[i]-Minprice;9             if(Prices[i] <minprice)TenMinprice =Prices[i]; One         } A         returnMax; -     } -}`

Python has been recently known, and occasionally the Python version is issued.

`1 classsolution (object):2     defMaxprofit (Self, prices):3         """4 : Type Prices:list[int]5 : Rtype:int6         """7         ifLen (prices) = =0:8             return09Max =0TenMinprice =Prices[0] One          A          forPriceinchPrices: -             ifMax < price-Minprice: -max = Price-Minprice the             ifPrice <Minprice: -Minprice = Price -                  -         returnMax`

121. Best time to Buy and Sell Stock

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.