LeetCode Best Time to Buy and Sell Stock

原创 2015年07月07日 14:36:47

Description:

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.

Solution:

题目的意思理解了我半天。

就是给定一个股票的数组,要求如何使得赚取的股票利润最大。也就是最大值减去最小值。

但是注意一点,股票是有时间的,从正过来的顺序,复杂度是O(n^2),但是按照时间反过来的顺序,可以降一维的复杂度,变成O(n)。

import java.util.*;

public class Solution {
	public int maxProfit(int[] prices) {
		if (prices.length == 0)
			return 0;
		int max = 0, maxPrice = prices[prices.length - 1];
		for (int i = prices.length - 2; i >= 0; i--) {
			maxPrice = Math.max(maxPrice, prices[i]);
			max = Math.max(max, maxPrice - prices[i]);
		}

		return max;
	}
}



【LeetCode-面试算法经典-Java实现】【121-Best Time to Buy and Sell Stock(最佳买卖股票的时间)】

【121-Best Time to Buy and Sell Stock(最佳买卖股票的时间)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】原题  Say you have a...

Leetcode 121. Best Time to Buy and Sell Stock

噢?一脸黑人问号,这道题目怎么会比之前那题通过率更低?刷完才发现,好像解题方式完全不同,题目的含义大相径庭。题目Say you have an array for which the ith elem...

leetcode 188---Best Time to Buy and Sell Stock IV

问题描述:Say you have an array for which the ith element is the price of a given stock on day i. 给你一个数组...
  • will130
  • will130
  • 2015年05月29日 13:36
  • 266

LeetCode(123) Best Time to Buy and Sell Stock III (Java)

题目如下: Say you have an array for which the ith element is the price of a given stock on day i. Desig...

leetcode -- Best Time to Buy and Sell Stock III --重点

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/参考: http://www.cnblogs.com/zuoyua...
  • xyqzki
  • xyqzki
  • 2015年12月10日 22:59
  • 247

[leetcode]Best Time to Buy and Sell Stock I&II

public int maxProfit(int[] prices) { int len=prices.length; if(len==2) r...

LeetCode122. Best Time to Buy and Sell Stock II题解

今天讨论一道让我想的过于复杂的题目:一道有关股票买卖的问题。题目描述:Say you have an array for which the i th element is the price of ...
  • lby0910
  • lby0910
  • 2017年04月06日 16:18
  • 300

Best Time to Buy and Sell Stock 系列问题(leetcode)

关键词: 动态规划,分治121. Best Time to Buy and Sell Stock题目地址 https://leetcode.com/problems/best-time-to-bu...

LeetCode--Best Time to Buy and Sell Stock IV(DP + 滚动数组)

题目:https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/

[Leetcode] 123. Best Time to Buy and Sell Stock III 解题报告

题目: Say you have an array for which the ith element is the price of a given stock on day i. ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode Best Time to Buy and Sell Stock
举报原因:
原因补充:

(最多只允许输入30个字)