前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode: Best Time to Buy and Sell Stock

Leetcode: Best Time to Buy and Sell Stock

作者头像
卡尔曼和玻尔兹曼谁曼
发布2019-01-22 15:55:28
3080
发布2019-01-22 15:55:28
举报
文章被收录于专栏:给永远比拿愉快

题目: Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

思路分析: 给定一个数组,数组中第i个元素代表第i天股票的价格。通过一次交易(即一次买入和一次卖出)获得最大的收益。 因为我们要以低价买入,以高价卖出才能获得最大收益。所以这道题目转换为数学问题,即对于数组prices[],计算prices[j]-prices[i]的最大值,而且要求j>i(这一点很重要),不是单纯地计算最大值和最小值之差。

C++参考代码:

代码语言:javascript
复制
class Solution
{
public:
    int maxProfit(vector<int> &prices)
    {
        vector<int>::size_type size = prices.size();
        if (0 == size) return 0;
        int min = prices[0];
        int result = 0;
        for (size_t i = 1; i < size; ++i)
        {
            if (prices[i] < min) min = prices[i];
            else if (prices[i] - min > result) result = prices[i] - min;

        }
        return result;
    }
};

C#参考代码:

代码语言:javascript
复制
public class Solution
{
    public int MaxProfit(int[] prices)
    {
        if (prices.Length == 0) return 0;
        int min = prices[0];
        int result = 0;
        for (int i = 1; i < prices.Length; ++i)
        {
            if (prices[i] < min) min = prices[i];
            else if (prices[i] - min > result) result = prices[i] - min;
        }
        return result;
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2015年04月05日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档