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 { //Time: O(n) Space: O(1) public int maxProfit(int[] prices) { if (prices == null || prices.length <= 1) { return 0; } int profit = 0; int min = prices[0]; for (int i = 1; i < prices.length; i++) { profit = Math.max(profit, prices[i] - min); min = Math.min(min, prices[i]); } return profit; } }
Say you have an array for which the ith element is the price of a given stock on day i.
比较直观的一道题,比较相邻的价格,如果后者大于前者,就把差值加进利润。
public class Solution { //Time: O(n) Space: O(1) public int maxProfit(int[] prices) { if (prices == null || prices.length <= 1) { return 0; } int profit = 0; for (int i = 1; i < prices.length; i++) { if (prices[i] > prices[i - 1]) { profit += prices[i] - prices[i - 1]; } } return profit; } }
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Best Time to Buy and Sell Stock的升级版。进行两次DP,第一次记录在时间点i前卖一次股票的收益,第二次记录在时间点i后卖一次股票的收益。
public class Solution { //Time: O(n) Space: O(n) public int maxProfit(int[] prices) { if (prices == null || prices.length <= 1) { return 0; } int max = prices[prices.length - 1]; int min = prices[0]; int[] pre = new int[prices.length];//存储在此点之前卖股票的收益 int[] post = new int[prices.length];//存储在此点之后卖股票的收益 for (int i = 1; i < prices.length; i++) { pre[i] = Math.max(pre[i - 1], prices[i] - min); min = Math.min(min, prices[i]); } for (int i = prices.length - 2; i >= 0; i--) { post[i] = Math.max(post[i + 1], max - prices[i]); max = Math.max(max, prices[i]); } max = 0; for (int i = 0; i < prices.length; i++) { max = Math.max(max, pre[i] + post[i]); } return max; } }
No comments:
Post a Comment