题解 | #买卖股票的最好时机(一)#
买卖股票的最好时机(一)
https://www.nowcoder.com/practice/64b4262d4e6d4f6181cd45446a5821ec
import java.util.*;
public class Solution {
/**
*
* @param prices int整型一维数组
* @return int整型
*/
public int maxProfit (int[] prices) {
int len = prices.length;
if(len < 2) {
return 0;
}
int[][] maxProfit = new int[len][2];
// 初始化
maxProfit[0][0] = 0;
maxProfit[0][1] = -prices[0];
for (int i = 1; i < len; i++) {
maxProfit[i][0] = Math.max(maxProfit[i-1][0],maxProfit[i-1][1] + prices[i]);
maxProfit[i][1] = Math.max(maxProfit[i-1][1],-prices[i]);
}
return maxProfit[len-1][0];
}
}
public class Solution {
/**
*
* @param prices int整型一维数组
* @return int整型
*/
public int maxProfit (int[] prices) {
int len = prices.length;
if(len < 2) {
return 0;
}
int[][] maxProfit = new int[len][2];
// 初始化
maxProfit[0][0] = 0;
maxProfit[0][1] = -prices[0];
for (int i = 1; i < len; i++) {
maxProfit[i][0] = Math.max(maxProfit[i-1][0],maxProfit[i-1][1] + prices[i]);
maxProfit[i][1] = Math.max(maxProfit[i-1][1],-prices[i]);
}
return maxProfit[len-1][0];
}
}