假设有一个数组,它的第i个元素是一支给定的股票在第i天的价格。如果你最多只允许完成一次交易(例如,一次买卖股票),设计一个算法来找出最大利润。
样例
给出一个数组样例 [3,2,3,1,2], 返回 1
解题思路1:
贪心算法,顺序扫描股票价格,找到截至当天最低的股票价格MinPrice,最高的利润profit。
public class Solution {
/**
* @param prices: Given an integer array
* @return: Maximum profit
*/
public int maxProfit(int[] prices) {
// write your code here
if(prices==null || prices.length<2)
return 0;
int minPrice = prices[0];
int profit = 0;
for(int i=1 ; i<prices.length ; i++){
minPrice = Math.min(minPrice, prices[i]);
profit = Math.max(profit, prices[i]-minPrice);
}
return profit;
}
}
解题思路2:
动态规划。设dp[i]是[0,1,2...i]区间的最大利润,则该问题的一维动态规划方程如下:
dp[i] = max{dp[i-1], prices[i] - minPrice[i]} ,minPrice[i]是区间[0,1,2...,i]内的最低价格
public class Solution {
/**
* @param prices: Given an integer array
* @return: Maximum profit
*/
public int maxProfit(int[] prices) {
// write your code here
if(prices==null || prices.length<2)
return 0;
int[] dp = new int[prices.length];
int[] minPrice = new int[prices.length];
dp[0] = 0;
minPrice[0] = prices[0];
for(int i=1 ; i<prices.length ; i++){
minPrice[i] = Math.min(minPrice[i-1], prices[i]);
dp[i] = Math.max(dp[i-1], prices[i]-minPrice[i]);
}
return dp[dp.length-1];
}
}