给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
/** * 第一天作为初始judge,从第二天开始比较 * 第二天大于第一天,total+=第二天-第一天 * 第二天小于第一天,judge值更新为第二天的 * 加入一个boolean值作为是否持有股票,因为持有股票只能卖,没有股票只能买 * 初始都是没有股票, * */ package selStock; /** * @author liuchenyu * @date Dec 2, 2019 */ public class Solutions { public static int maxProfit(int[] prices) { if(prices.length<2) return 0; boolean hasStock = false; int total = 0; int judge = prices[0]; for (int i = 1; i < prices.length ; i++) { if (hasStock == false) { if (prices[i] > judge) { total += prices[i] - judge; judge = prices[i]; hasStock = true; System.out.println(total); } else { judge = prices[i]; System.out.println(total); } } else { if(prices[i] < judge) { judge = prices[i]; hasStock = false; //i++; System.out.println(total); } else { total += prices[i]-judge; judge = prices[i]; System.out.println(total); } } } return total; } public static void main(String[] args) { int[] prices = { 7, 1, 5, 3, 6, 4 }; System.out.println(maxProfit(prices)); } }
类似寻找递增数列和递减数列
如果股价一直下降,那么一直不买,直到发现上涨,那么就在上涨前一天买
如果股价一直上升,那么一直不卖,直到发现下降,那么就在下降前一天卖
加入一个判断是否持有股票的变量,因为手里有股票和没有股票的逻辑是不一样的
持有股票则希望一直是递增,空仓则希望一直下降。
浙公网安备 33010602011771号