ARTICLE DETAIL

资讯详情

深耕网站视觉设计与运营推广的一线实战洞察。

DeepSeek LeetCode 122. 买卖股票的最佳时机 II C语言实现

DeepSeek    LeetCode 122. 买卖股票的最佳时机 II C语言实现 LeetCode 122 题可以用贪心算法解决只要后一天价格比前一天高就把差值累加到利润中。C 语言实现intmaxProfit(int*prices,intpricesSize){intprofit0;for(inti1;ipricesSize;i){if(prices[i]prices[i-1]){profitprices[i]-prices[i-1];}}returnprofit;}思路说明股票价格可以看作多个上涨区间。对于每个上涨区间例如1 - 3 - 5可以· 第 1 天买入第 2 天卖出赚 3 - 1 2· 第 2 天再买入第 3 天卖出赚 5 - 3 2总利润为 4等价于第 1 天买入、第 3 天卖出5 - 1 4。所以只需要统计所有相邻两天中后一天比前一天高的差值之和。复杂度· 时间复杂度O(n)· 空间复杂度O(1)示例#includestdio.hintmaxProfit(int*prices,intpricesSize){intprofit0;for(inti1;ipricesSize;i){if(prices[i]prices[i-1]){profitprices[i]-prices[i-1];}}returnprofit;}intmain(){intprices[]{7,1,5,3,6,4};intsizesizeof(prices)/sizeof(prices[0]);printf(%d\n,maxProfit(prices,size));// 输出 7return0;}
返回列表