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.
Solution 1: Use DP. dp[i] is max profit if sell at day i. Optimize space to O(n).
public class Solution {
public int maxProfit(int[] prices) {
int dp=0, max=0;
for (int i=0; i<prices.length; i++) {
if (i==0) dp=0;
else dp=Math.max(0,dp+prices[i]-prices[i-1]);
max=Math.max(max,dp);
}
return max;
}
}
没有评论:
发表评论