NC7 买卖股票的最好时机
描述
假设你有一个数组,其中第\ i i 个元素是股票在第\ i i 天的价格。
你有一次买入和卖出的机会。(只有买入了股票以后才能卖出)。请你设计一个算法来计算可以获得的最大收益。
示例1
输入:
[1,4,2]
复制
返回值:
3
复制
示例2
输入:
[2,4,1]
复制
返回值:
2
import java.util.*;
public class Solution {
/**
*
* @param prices int整型一维数组
* @return int整型
*/
public int maxProfit (int[] prices) {
// write code here
if(prices == null || prices.length == 0){
return 0 ;
}
int[] f = new int[prices.length] ;
int[] dp = new int[prices.length] ;
f[0] = 0 ;
dp[0] = 0 ;
for(int i = 1 ; i < prices.length ; i++){
f[i] = prices[i] - prices[i-1] ;
dp[i] = Math.max(dp[i-1] + f[i] , f[i]);
}
int max = 0 ;
for(int i = 0 ; i < prices.length ; i++){
max = Math.max(max , dp[i]) ;
}
return max ;
}
}