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.
这道题可以转化为最大子段和问题,值得学习。
建议和leetcode 188. Best Time to Buy and Sell Stock IV 最大子段和 、leetcode 123. Best Time to Buy and Sell Stock III 最大k次字段和 + DP 、leetcode 122. Best Time to Buy and Sell Stock II 最大子段和 + DP 、leetcode 121. Best Time to Buy and Sell Stock 最大字段和问题 + DP 、leetcode 714. Best Time to Buy and Sell Stock with Transaction Fee 动态规划DP 和leetcode 309. Best Time to Buy and Sell Stock with Cooldown 动态规划DP一起学习。
还有这一道题哟leetcode 53. Maximum Subarray DP+最大子串和
代码如下:
/*
* 算法导论说这个问题可以转华为最大字段和的问题
* */
public class Solution
{
public int maxProfit(int[] prices)
{
if(prices==null || prices.length<=0)
return 0;
int []num=new int[prices.length-1];
for(int i=1;i<prices.length;i++)
num[i-1]=prices[i]-prices[i-1];
return getMaxSum(num);
}
//动态规划求解最大子段和
int getMaxSum(int[] num)
{
int sum=0,dp=0;
for (int i = 0; i < num.length; i++)
{
if(dp>0)
dp=dp+num[i];
else
dp=num[i];
sum=Math.max(dp, sum);
}
return sum;
}
}
下面是C++的做法,就是一个很经典的DP动态规划问题,
代码如下:
#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
using namespace std;
class Solution
{
public:
int maxProfit(vector<int>& p)
{
if (p.size() <= 1)
return 0;
vector<int> dp(p.size()-1,0);
for (int i = 0; i < dp.size(); i++)
dp[i] = p[i + 1] - p[i];
int sum = 0, b = 0;
for (int i = 0; i < dp.size(); i++)
{
if (b > 0)
b += dp[i];
else
b = dp[i];
sum = max(sum, b);
}
return sum;
}
};
还可以这么做
#include <iostream>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <queue>
#include <stack>
#include <string>
#include <climits>
#include <algorithm>
#include <sstream>
#include <functional>
#include <bitset>
#include <numeric>
#include <cmath>
#include <regex>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;
class Solution
{
public:
int maxProfit(vector<int>& p)
{
if (p.size() <= 1)
return 0;
else
return calak(p, 1);
}
int calak(vector<int>& p, int k)
{
vector<int> buy(k, INT_MIN);
vector<int> sell(k,INT_MIN);
for (int i = 0; i < p.size(); i++)
{
buy[0] = max(buy[0], -p[i]);
sell[0] = max(sell[0], buy[0] + p[i]);
for (int j = 1; j < k; j++)
{
buy[j] = max(buy[j],sell[j-1]-p[i]);
sell[j] = max(sell[j], buy[j] + p[i]);
}
}
return sell[k - 1];
}
};