标签:
I题
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.
Subscribe to see which companies asked this question
解答:采用动态规划解法,遍历数组更新当前最小值,并用当前值减去最小值与当前最大利润进行比较,更新最大利润。
public class Solution { public int maxProfit(int[] prices) { if (prices == null || prices.length == 0) { return 0; } int min = Integer.MAX_VALUE; int profit = 0; for (int i : prices) { min = Math.min(min, i); profit = Math.max(i - min, profit); } return profit; } }
II
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 as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Subscribe to see which companies asked this question
解答:采用贪心算法,记录相邻两天的差值,大于零则加到利润总量中。
public class Solution { public int maxProfit(int[] prices) { int profit = 0; for (int i = 0; i < prices.length - 1; i++) { int pro = prices[i + 1] - prices[i]; if (pro > 0) { profit += pro; } } return profit; } }
Best Time to Buy and Sell Stock系列
标签:
原文地址:http://www.cnblogs.com/shinning/p/5314952.html