博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 121. Best Time to Buy and Sell Stock
阅读量:4511 次
发布时间:2019-06-08

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

Problem: 

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.

 

Thought:

from back to front, refresh the maximum price after prices[i] on each loop    O(n)

 

Code C++:

class Solution {public:    int maxProfit(vector
& prices) { int profit = 0; if (prices.size() <= 1) { return profit; } int max_price = prices.back(); for (int i = prices.size() - 2; i >= 0; i--) { if (prices[i] < max_price) { int diff = max_price - prices[i]; profit = profit > diff ? profit : diff; } else { max_price = prices[i]; } } return profit; }};

 

转载于:https://www.cnblogs.com/gavinxing/p/5621443.html

你可能感兴趣的文章
领域对象驱动开发:来吧,让我们从对象开始吧
查看>>
mysql分区分表讲解
查看>>
java编程思想读书笔记三(11-21)
查看>>
luogu P5302 [GXOI/GZOI2019]特技飞行
查看>>
EntityFramework 开始小试
查看>>
234 Palindrome Linked List
查看>>
Keil-MDK编译完成后代码大小
查看>>
ArcGIS JS 学习笔记4 实现地图联动
查看>>
6.3确认网站色调-主色辅色背景色
查看>>
CSS Hack技术介绍及常用的Hack技巧
查看>>
【精解】EOS智能合约演练
查看>>
树的遍历(非递归)
查看>>
poj 3176 Cow Bowling
查看>>
振兴中华
查看>>
HDU3047 Zjnu Stadium(带权并查集)
查看>>
最大流模板
查看>>
UVA 10080 Gopher II
查看>>
[转载]网站分析的最基本度量(1)—Visit
查看>>
socket 简单c/s通信
查看>>
思维导图软件
查看>>