博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode Best Time to Buy and Sell Stock
阅读量:4185 次
发布时间:2019-05-26

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

题目解析:

注意只能够买一次和卖一次股票
其实这个题目就是最大子列和的变形,他是求的矩阵【23,24,27,18,23,19,31】这样的一个矩阵的最大利润,当有些天的利润为负值,则另begin移到这一天作为开始,这与最大子列和的思想完全相同。
可参考我的最大子列和程序

// Author : yqtao// Date   : 2016-6.19// Email  :yqtao@whu.edu.cn/************************************************************************************ 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.***********************************************************************************/#include "stdafx.h"#include 
#include
#include
#include
#include
using namespace std;int maxProfit(vector
&price){ int begin = 0, end = 0, max = 0; for (int i = 0; i < price.size(); i++) { end = i; int delta = price[end] - price[begin]; if (delta <= 0) begin = i; if (delta > 0) max = delta; } return max;}//测试int main(){ vector
price = { 23,24,27,18,23,19,31 }; cout << maxProfit(price) << endl;//答案13即31-18=13利益最大 //即利益为18的那天入手,利益31天出手,利益最大}

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

你可能感兴趣的文章