方法一:
高买低卖
后一天价格 > 前一天价格
买入 利润为差值
public class Solution {
public int MaxProfit(int[] prices) {
int price = 0, profit = 0;
bool buystatus = false;
for (int i=0; i<prices.Length-1; i++) {
if(prices[i] < prices[i+1]) {
if(!buystatus) {
buystatus = true;
price = prices[i];
}
if(i == prices.Length-2) {
if(buystatus) {
buystatus = false;
profit += prices[i+1] - price;
}
}
}
else {
if(buystatus) {
buystatus = false;
profit += prices[i] - price;
}
}
}
return profit;
}
}
方法二:
动态规划
每天由三种情况:
1:买入 2:没买 3:卖出
买入和没买:利润为上一天的利润
卖出:利润为上一天利润加上今天利润
public class Solution {
public int MaxProfit(int[] prices) {
int hold = -prices[0];
int unhold = 0;
for (int i=1; i<prices.Length; i++) {
unhold = max(unhold, hold + prices[i]);
hold = max(hold, unhold - prices[i]);
}
return unhold;
}
public int max(int a, int b) {
return a>b?a:b;
}
}
public class Solution {
public int MaxProfit(int[] prices) {
if (prices == null || prices.length < 2)
return 0;
int maxprice = 0;
for( int i=0; i<prices.Length-1; i++ ) {
if( prices[i+1] - prices[i] > 0 ){
maxprice = maxprice + (prices[i+1] - prices[i]);
}
}
return maxprice;
}
}