---
title: "Best Time to Buy and Sell Stock"
author: "dugu108"
date: "2013-01-26T14:31:47Z"
tags: []
categories: ["行业应用"]
slug: "best-time-to-buy-and-sell-stock"
draft: false
lastmod: "2013-01-26T14:31:47Z"
id: 1776071
url: "https://dugu108.iteye.com/blog/1776071"
---

Say you have an array for which the *i*th 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;
	}
}
```