ITeye博客

Best Time to Buy and Sell Stock

dugu108 · 2013-01-26 14:31 · Leetcode · 行业应用 · Markdown

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.

 

public class Solution {
	public int maxProfit(int[] prices) {
		// Start typing your Java solution below
		// DO NOT write main() function
		if (prices == null || prices.length <= 0)
			return 0;
		int min = 0;
		int max = 0;
		int result = 0;
		for (int i = 1; i <= prices.length - 1; i++) {
			if (prices[i] > prices[max])
				max = i;
			if (prices[i] < prices[min]) {
				if (i > max) {
					if (result < prices[max] - prices[min]) {
						result = prices[max] - prices[min];
					}
					max = i;
				}
				min = i;
			}
		}

		if (result < prices[max] - prices[min]) {
			result = prices[max] - prices[min];
		}

		return result;
	}
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。