2014
11-19

# LeetCode-Best Time to Buy and Sell Stock[贪心]

### Best Time to Buy and Sell Stock

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.

// LeetCode, Best Time to Buy and Sell Stock
// 时间复杂度O(n)，空间复杂度O(1)
class Solution {
public:
int maxProfit(vector<int> &prices) {
if (prices.size() < 2) return 0;
int profit = 0;  // 差价，也就是利润
int cur_min = prices[0]; // 当前最小

for (int i = 1; i < prices.size(); i++) {
profit = max(profit, prices[i] - cur_min);
cur_min = min(cur_min, prices[i]);
}
return profit;
}
};


Java代码:

public class Solution {

public int maxProfit(int[] prices) {
if(prices.length == 0) return 0;
int low = prices[0];
int ans = 0;
for(int i=1; i<prices.length; i++){
if(prices[i] < low) low = prices[i];
else if(prices[i] - low > ans) ans = prices[i] - low;
}
return ans;
}
}

1. 我还有个问题想请教一下，就是感觉对于新手来说，递归理解起来有些困难，不知有没有什么好的方法或者什么好的建议？