1. 程式人生 > >Leetcode 121: Best Time to Buy and Sell Stock

Leetcode 121: Best Time to Buy and Sell Stock

output inpu return ive price interview not don style

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 sell one share of the stock), design an algorithm to find the maximum profit.

Example 1:

Input: [7, 1, 5, 3, 6, 4]
Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

Example 2:

Input: [7, 6, 4, 3, 1]
Output: 0

In this case, no transaction is done, i.e. max profit = 0.

 1 public class Solution {
 2     public int MaxProfit(int[] prices) {
 3         if (prices.Length < 2) return 0;
 4         
 5         int curMin = Int32.MaxValue, result = 0;
 6         for
(int i = 0; i < prices.Length; i++) 7 { 8 curMin = Math.Min(curMin, prices[i]); 9 result = Math.Max(result, prices[i] - curMin); 10 } 11 12 return result; 13 } 14 15 public int MaxProfit1(int[] prices) { 16 if (prices.Length < 2
) return 0; 17 18 var maxRight = new int[prices.Length]; 19 20 int cur = 0; 21 for (int i = prices.Length - 1; i >= 0; i--) 22 { 23 cur = Math.Max(cur, prices[i]); 24 maxRight[i] = cur; 25 } 26 27 cur = 0; 28 for (int i = 0; i < prices.Length; i++) 29 { 30 cur = Math.Max(cur, maxRight[i] - prices[i]); 31 } 32 33 return cur; 34 } 35 }

Leetcode 121: Best Time to Buy and Sell Stock