LintCode--买卖股票的最佳时机

本文详细解析了LintCode平台上的买卖股票最佳时机问题,通过构建新数组记录每日涨幅并转化为最大子序列和问题,阐述了时间复杂度为O(n)的解决方案。代码示例涵盖了C++、Python和Java三种编程语言。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LintCode--best-time-to-buy-and-sell-stock(买卖股票的最佳时机)

原题链接:http://www.lintcode.com/zh-cn/problem/best-time-to-buy-and-sell-stock/


假设有一个数组,它的第i个元素是一支给定的股票在第i天的价格。如果你最多只允许完成一次交易(例如,一次买卖股票),设计一个算法来找出最大利润。

样例

给出一个数组样例 [3,2,3,1,2], 返回 1 


分析:

新建一个新的数组记录每天的涨幅,顺理成章转化为最大子序列和。

时间复杂度  O(n)


代码(C++、Python、Java):

class Solution {
public:
    /**
     * @param prices: Given an integer array
     * @return: Maximum profit
     */
    int maxProfit(vector<int> &prices) {
        // write your code here
        int n = prices.size();
        if (n <= 1) return 0;
        vector<int> trans;
        for (int i = 1; i <= n; i++)
            trans.push_back(prices[i] - prices[i-1]);
        int imax = 0, res = 0;
        for(int i = 0; i < n-1; i++){
            imax += trans[i];
            if (imax > res) res = imax;
            else if(imax < 0) imax = 0;
        }
        return res;
    }
};

class Solution:
    """
    @param prices: Given an integer array
    @return: Maximum profit
    """
    def maxProfit(self, prices):
        # write your code here
        n = len(prices)
        if n <= 1:
            return 0
        trans = [0 for i in range(n-1)]
        for i in range(n-1):
            trans[i] = prices[i+1] - prices[i]
        imax = 0
        res = 0
        for i in range(n-1):
            imax += trans[i]
            if imax > res:
                res = imax
            elif imax < 0:
                imax = 0
        return res

public class Solution {
    /**
     * @param prices: Given an integer array
     * @return: Maximum profit
     */
    public int maxProfit(int[] prices) {
        // write your code here
        int n = prices.length;
        if (n <= 1) return 0;
        int []trans = new int [n-1];
        for (int i = 0; i < n-1; i++)
            trans[i] = prices[i+1] - prices[i];
        int imax = 0, res = 0;
        for (int i = 0; i < n-1; i++){
            imax += trans[i];
            if (imax > res) res = imax;
            else if (imax < 0) imax = 0;
        }
        return res;
    }
}


LintCode 1817 - 分享巧克力 是一道经典的算法题目,通常涉及动态规划、贪心算法等知识。这道题的核心思想是如何将一块巧克力分成若干块,并让每块满足一定的条件。 ### 题目概述: 假设有一块 `m x n` 的巧克力网格图,每个格子表示一小块巧克力。你需要将其分给 K 个人,每个人获得连续的一段巧克力(可以横着切或竖着切)。目标是使得所有人的巧克力总和的最大值尽可能小。 --- ### 解法思路: #### 方法一:二分查找 + 模拟验证 我们可以采用“二分查找”的策略来解决这个问题。核心在于设定一个范围 `[min_val, sum_of_chocolate]`,其中 `min_val` 表示单个巧克力单元的最小值,而 `sum_of_chocolate` 则是整个巧克力表的所有数值之和。 步骤如下: 1. **确定搜索区间**:左边界设为数组中的最大元素 (因为至少一人要拿到这个数),右边界设为总和 (即所有人都拿一样的情况)。 2. **验证中间值是否可行**:对于当前猜测的最大值 mid,检查能否通过合理的切割分配方案,使得每个人的份额都不超过该值。 3. 根据结果调整左右边界直至找到最优解。 时间复杂度大约为 O(log(total_sum) * m * n) #### 示例代码片段(Python版): ```python def minimizeMaxShare(chocoGrid, k): def canSplit(max_allowed): # 实现判断是否能按照规则分割函数 total = sum(map(sum,chocogrid)) low , high= max([max(row) for row in chocogrid]),total while(low<high): mid=(low+high)//2 if(canSplit(mid)): high=mid else: low=mid+1 return low ``` --- ### 关键点总结: - 使用了高效的二分查找技巧降低暴力枚举的时间开销; - 结合实际场景构建辅助判定功能完成对潜在解答的有效评估;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值