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:Best Time to Buy and Sell Stock(买卖股票)系列

121. Best Time to Buy and Sell StockSay you have an array for which the ith element is the price of ...

[Leetcode]122. Best Time to Buy and Sell Stock II

122. Best Time to Buy and Sell Stock IISay you have an array for which the i-th element is the price...

LeetCode----best-time-to-buy-and-sell-stock-ii

题目描述 Say you have an array for which the ith element is the price of a given stock on day...

leetcode 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...

Best Time to Buy and Sell Stock III(leetcode)

题目: 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 III

Best Time to Buy and Sell Stock III  Say you have an array for which the ith element is the...

LeetCode OJ-121. Best Time to Buy and Sell Stock(股票问题)

121. Best Time to Buy and Sell Stock Say you have an array for which the ith element is the pri...

[LeetCode]123. Best Time to Buy and Sell Stock III

[LeetCode]123. Best Time to Buy and Sell Stock III题目描述思路动态规划 举例来说 index 0 1 2 3 4 5 ...

Leetcode Best Time to Buy and Sell Stock IV

Leetcode Best Time to Buy and Sell Stock IV,本题主要是找出最大值与买卖次数的关系,很快可以求得结果。卖买次数与k的关系分析 首先我们知道当次数不限时,只需要...

【LeetCode】Best Time to Buy and Sell Stock IV 动态规划dp解法(C++)

乍看此题有难度,实则解法有规律。
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

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