博客
关于我
Leetcode 121. 买卖股票的最佳时机(DAY 26) ---- 动态规划学习期
阅读量:207 次
发布时间:2019-02-28

本文共 1408 字,大约阅读时间需要 4 分钟。

代码实现与优化分析

在编写股票交易最大利润计算代码时,常见的思路是通过遍历所有价格数据,寻找最低买点和最高卖点,从而计算最大交易利润。然而,这种方法虽然直观,但在实际应用中往往效率较低,无法应对大规模数据的处理需求。

以下是两种实现方案:

第一种实现(C语言版本)

int maxProfit(int* prices, int pricesSize) {    int i, min = INT_MAX, max = -1, profit = -1;    for (i = 0; i < pricesSize; i++) {        if (prices[i] < min) {            min = prices[i];            max = prices[i];        } else {            if (max > -1) {                if (prices[i] - min > profit) {                    profit = prices[i] - min;                }            }        }    }    return profit;}

第二种实现(C++语言版本)

#include 
#include
class Solution {public: int maxProfit(std::vector
& prices) { int size = prices.size(); if (size == 0) return 0; int minBuy = prices[0]; int maxSell = 0; for (const auto& num : prices) { if (num - minBuy > maxSell) { maxSell = num - minBuy; } if (num < minBuy) { minBuy = num; } } return maxSell; }};

优化思路

  • 减少重复遍历:在第二种实现中,我们避免了重复遍历所有数据,直接在单个循环中维护当前的最低买点和最高卖点,从而减少了时间复杂度。

  • 逻辑优化:通过直接比较当前价格与最低买点之间的利润,避免了不必要的计算,使得代码更加简洁高效。

  • 异常处理:在第二种实现中,我们增加了对空数据集合的处理,确保程序在 Edge Case 中也能稳定运行。

  • 代码对比与分析

    • C语言版本:虽然直观,但在多次遍历数据时效率较低,且难以维护和扩展。
    • C++语言版本:通过优化逻辑,减少了不必要的比较操作,提升了运行效率,同时代码结构更加清晰,便于维护和扩展。

    总结

    选择合适的语言和算法设计至关重要。在实际应用中,C++版本的实现效率更高且代码质量更优。对于需要处理大规模数据的场景,建议采用第二种实现方案。

    转载地址:http://shji.baihongyu.com/

    你可能感兴趣的文章
    POJ 2488:A Knight&#39;s Journey
    查看>>
    SpringBoot为什么易学难精?
    查看>>
    poj 2545 Hamming Problem
    查看>>
    poj 2723
    查看>>
    poj 2763 Housewife Wind
    查看>>
    Qt笔记——模型/视图MVD 文件目录浏览器软件
    查看>>
    POJ 2892 Tunnel Warfare(树状数组+二分)
    查看>>
    poj 2965 The Pilots Brothers' refrigerator-1
    查看>>
    poj 3026( Borg Maze BFS + Prim)
    查看>>
    POJ 3041 - 最大二分匹配
    查看>>
    POJ 3041 Asteroids(二分匹配模板题)
    查看>>
    Qt笔记——标准文件对话框QFileDialog
    查看>>
    poj 3083 Children of the Candy Corn
    查看>>
    POJ 3083 Children of the Candy Corn 解题报告
    查看>>
    POJ 3253 Fence Repair C++ STL multiset 可解 (同51nod 1117 聪明的木匠)
    查看>>
    Qt笔记——控件总结
    查看>>
    poj 3262 Protecting the Flowers 贪心
    查看>>
    poj 3264(简单线段树)
    查看>>
    Qt笔记——布局管理三件套分割窗口、停靠窗口和堆栈窗口
    查看>>
    poj 3277 线段树
    查看>>