# 121 Buy and Sell Stock
input是一個int array,記錄連續n天的股票價格,
題目說可以買進再賣出,問最大淨利是多少。
Concept:
所以關鍵就是要在最低點買進,最高點賣出,且最低點index要比最高點index小。
用一個int min記錄目前最低點,一個int[] dp記錄當天最大淨利,一個int profit記錄最大淨利。
Pseudocode:
dp[0] = prices[0]
min = prices[0]
for each element in prices
dp[i] = prices[i]-min
min = price[i] < min ? price[i] : min
profit = dp[i] > profit ? dp[i] : profit
return profit
完整程式碼:
public class Solution {
public int maxProfit(int[] prices) {
if(prices.length == 0) return 0;
int[] dp = new int[prices.length];
dp[0] = prices[0];
int min = prices[0];
int profit = 0;
for(int i=1; i<prices.length; i++){
dp[i] = prices[i] - min;
min = prices[i] < min ? prices[i] : min;
profit = dp[i] > profit ? dp[i] : profit;
}
return profit;
}
}
Optimize: 其實可以不用dp陣列來記,用一個變數來記profit就可以了
public class Solution {
public int maxProfit(int[] prices) {
int ans=0;
if(prices.length==0) return ans;
int bought=prices[0];
for(int i=1;i<prices.length;i++){
if(prices[i]>bought){
if(ans<(prices[i]-bought))
ans=prices[i]-bought;
}
else
bought=prices[i];
}
return ans;
}
}