LeetCode-Best Time to Buy and Sell Stock-解题报告

来源:互联网 发布:图片加字软件 编辑:程序博客网 时间:2024/05/03 08:42

原题链接https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

Say you have an array for which the ith element is the price of a given stock on dayi.

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.

给你一个数组,nums[i]表示第i的股价,最多交易一次,问作大利益是多少。


很简单,求出用 p[i]表示第i天与前一天的股票价格差,所以p[i] = nums[i] - nums[i-1],p[i] + p[i-1] = nums[i] - nums[i-2],所以将题目转化成了最大子段和的问题。为了节省空间,我将他们的差保存在了给定的数组nums中,nums[i-1]表示第i天与i-1天的股票差。

复杂度为o(n)

<pre name="code" class="cpp">class Solution {public:    int maxProfit(vector<int>& prices) {    if (prices.size() < 2)return 0;for (int i = 1; i < prices.size(); ++i)    prices[i - 1] = prices[i] - prices[i - 1];        int ans = -1, tmp = 0;    for (int i = 0; i < prices.size() - 1; ++i)    {    if (tmp > ans) ans = tmp;    if (tmp >= 0)tmp += prices[i];    else tmp = 0, tmp += prices[i];}    if (tmp >ans) ans = tmp;    return ans;    }};






0 0
原创粉丝点击