股票的最大利润

题目

https://leetcode-cn.com/problems/gu-piao-de-zui-da-li-run-lcof/

解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public int maxProfit(int[] prices) {
if(prices==null || prices.length==0) return 0;

int len = prices.length;
int res = 0;
int buyInCost = prices[0];

for (int i = 1; i < len; i++) {
buyInCost = Math.min(buyInCost, prices[i]);
res = Math.max(res, prices[i]-buyInCost);
}
return res;
}

public int maxProfit2(int[] prices) {
if(prices==null || prices.length==0) return 0;

int len = prices.length;
int[] dp = new int[len]; // 前i个日最大利润
dp[0]=0;
int minValue = prices[0];
for (int i = 1; i < len; i++) {
minValue = Math.min(minValue, prices[i]);
dp[i] = Math.max(dp[i-1], prices[i]-minValue);
}
return dp[len-1];
}
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×