首页 > 代码库 > Best Time to Buy and Sell Stock I && II && III
Best Time to Buy and Sell Stock I && II && III
题目1: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 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) { int size = prices.length; if (size == 0){ return 0; } int maxPrice = prices[size-1];//初始化最大price int maxMoney = 0;//初始化利润值 for (int i=size-1; i>=0; --i){ maxPrice = maxPrice > prices[i] ? maxPrice : prices[i];//假设第i天的值大于最大price,则更新最大price的值 maxMoney = maxMoney > (maxPrice - prices[i]) ? maxMoney : (maxPrice - prices[i]);//更新最大利润值 } return maxMoney; } }
题目2: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 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).
AC代码:
public class Solution { public int maxProfit(int[] prices) { int profit = 0; int size = prices.length; if (size < 2){ return profit; } for (int index=1; index<size; ++index){ int value = http://www.mamicode.com/prices[index] - prices[index-1];>
题目3:
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.
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).
用right[i]来表示[i,...,n-1]上的最大利润
public class Solution { public int maxProfit(int[] prices) { int size = prices.length; if (size < 2) return 0; int[] left = new int[size]; int[] right = new int[size]; int minValue = http://www.mamicode.com/prices[0];>left[i-1] : (prices[i] - minValue); minValue = http://www.mamicode.com/minValue < prices[i] ? minValue : prices[i];>
right[i+1] : (maxValue - prices[i]); maxValue = http://www.mamicode.com/maxValue > prices[i] ?
maxValue : prices[i]; } int profit=0; for (int i=0; i<size; ++i){ profit = profit > (left[i] + right[i]) ? profit : (left[i] + right[i]); } return profit; } }
Best Time to Buy and Sell Stock I && II && III