This is the 26th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021.
describe
Given an array prices, its ith element prices[I] represents the price of a given stock on day I.
You can only buy the stock on one day and sell it on a different day in the future. Design an algorithm to calculate the maximum profit you can make.
Return the maximum profit you can make from the transaction. If you can’t make any profit, return 0.
Example 1: input: [7,1,5,3,6,4] output: 5 explanation: buy on day 2 (stock price = 1) and sell on day 5 (stock price = 6), maximum profit = 6-1 = 5. Note that the profit cannot be 7-1 = 6, because the selling price needs to be higher than the buying price; Also, you can't sell stocks before you buy them. Example 2: input: prices = [7,6,4,3,1] output: 0 explanation: in this case, no transaction is completed, so the maximum profit is 0.Copy the code
Tip:
1 <= prices.length <= 105
0 <= prices[i] <= 104
Approvals 605,132 Submissions 1,055,538
Problem.
This problem requires us to do two things, one is to find the lowest purchase price, and the other is to find the highest yield.
Notice that we only have one chance to buy and sell.
Look for the right buying price, constantly compare the current number, and replace if the current number is small;
If the current number is large, the selling price is the current price (because the buying price is the previous number, so you can sell), subtract and see how much profit there is, regardless of the negative number, and then compare this profit with the maximum profit.
This cycle is where you get the most out of it.
Knock code!
public int maxProfit(int[] prices) { int maxProfit=0; Int minPrice =prices[0]; int minPrice =prices[0]; for (int i = 1; i < prices.length; i++) { int price = prices[i]; If (price<minPrice){// minPrice=price; continue; } int profit = price - minPrice; MaxProfit =profit>maxProfit? profit:maxProfit; } return maxProfit; }Copy the code
Do it right once and do it so well! I really great!
That’s all for today.
Here is a programmer Xu Xiaobai, daily algorithm [is] my new open a column, primary record my daily learning algorithm, here also hope that I can stick to the daily learning algorithm, don’t know whether this article style you like, don’t mean you free praise, your thumb up, collection, and comments are after work I insist on more power.