# Best Time to Buy and Sell Stock

## Question

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
Given an example [3,2,3,1,2], return 1


## 题解

### Python

class Solution:
"""
@param prices: Given an integer array
@return: Maximum profit
"""
def maxProfit(self, prices):
if prices is None or len(prices) <= 1:
return 0

profit = 0
cur_price_min = 2**31 - 1
for price in prices:
profit = max(profit, price - cur_price_min)
cur_price_min = min(cur_price_min, price)

return profit


### C++

class Solution {
public:
/**
* @param prices: Given an integer array
* @return: Maximum profit
*/
int maxProfit(vector<int> &prices) {
if (prices.size() <= 1) return 0;

int profit = 0;
int cur_price_min = INT_MAX;
for (int i = 0; i < prices.size(); ++i) {
profit = max(profit, prices[i] - cur_price_min);
cur_price_min = min(cur_price_min, prices[i]);
}

return profit;
}
};


### Java

public class Solution {
/**
* @param prices: Given an integer array
* @return: Maximum profit
*/
public int maxProfit(int[] prices) {
if (prices == null || prices.length <= 1) return 0;

int profit = 0;
int curPriceMin = Integer.MAX_VALUE;
for (int price : prices) {
profit = Math.max(profit, price - curPriceMin);
curPriceMin = Math.min(curPriceMin, price);
}

return profit;
}
}


## Reference

• soulmachine 的卖股票系列