题目分析
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.
Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example 2:
Input: [7, 6, 4, 3, 1]
Output: 0
In this case, no transaction is done, i.e. max profit = 0.
题目要求是只能买入卖出一次,问最大利润。
代码
解法一
class Solution {
public int maxProfit(int[] prices) {
int res = 0;
int cursum = 0;
for(int i = 1; i < prices.length; i++) {
// 判断当前的总和是不是小于0
// 如果当前总和小于0了,那么直接更新当前总和
if(cursum <= 0) {
cursum = prices[i] - prices[i - 1];
} else {
cursum += prices[i] - prices[i - 1];
}
if(cursum > res) {
res = cursum;
}
}
return res;
}
}
解法二:动态规划解法
public class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length <= 1) {
return 0;
}
// 动态规划的解法
// 任一时刻都可以选择卖或者不卖
int res = 0;
int minPrice = prices[0];
for(int i = 1; i < prices.length; i++) {
// 更新这个点之前的最小价格
if(prices[i - 1] < minPrice) {
minPrice = prices[i - 1];
}
// 如果在这个时间点卖或得得利润比上个时间点多
if(prices[i] - minPrice > res) {
res = prices[i] - minPrice;
}
}
return res;
}
}
网友评论