题目要求
给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。
你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。
力扣题目链接
背景
2021年5月 面试字节杭州研发中心后端研发岗位时候一面的面试题
其实2016年11月在北京面试老虎证券时候,面试官也出的是这道题目,遗憾当时没有搞定!
基础版本题目
public int maxProfit(int[] prices) {if (prices.length <= 1) {return 0;}int max = 0;for (int x = 0; x < prices.length; x++) {for (int y = x + 1; y < prices.length; y++) {int temp = prices[x] - prices[y];if (temp < 0) {if (Math.abs(temp) >= max) {max = Math.abs(temp);}}}}return max;}public int maxProfit(int[] prices) {if (prices.length <= 1) {return 0;}int min = prices[0], max = 0;for (int i = 1; i < prices.length; i++) {max = Math.max(max, prices[i] - min);min = Math.min(min, prices[i]);}return max;}
进阶版本
第一道题目快速写完之后,面试官看写的很快,一次AC。立马让尝试进阶版本题目😅
题目发生了变化,要求可以一天之内多次买卖,追求最大收益。
// 贪心func maxProfit(prices []int) int {profit := 0for i := 0; i < len(prices)-1; i++ {if prices[i+1] > prices[i] {profit += prices[i+1] - prices[i]}}return profit}// 动态规划
