121.LeetCode Best Time to Buy and Sell Stock(easy)[数组 动态规划]
来源:互联网 发布:淘宝联盟站长 编辑:程序博客网 时间:2024/05/28 23:20
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.
Example 1:
Input: [7, 1, 5, 3, 6, 4]Output: 5max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example 2:
Input: [7, 6, 4, 3, 1]Output: 0In this case, no transaction is done, i.e. max profit = 0.
这个题是要通过解决购买一次进股票,然后选择某天销售取得最大利润的问题。这里利用dp数据存放到目前为止价格最小的股票价格,然后通过profit保存当前为止的最大的利润。
class Solution {public: int maxProfit(vector<int>& prices) { int n = prices.size(); if(n<=1) return 0; int dp[n];//存放到目前为止最小的元素 dp[0] = prices[0]; int profit = 0; for(int i=1;i<n;i++) { if(prices[i]<dp[i-1]) { dp[i] = prices[i]; }else{ dp[i] = dp[i-1]; int temp = prices[i]- dp[i-1]; if(temp>profit) profit = temp; } } return profit; }};
0 0
- 121.LeetCode Best Time to Buy and Sell Stock(easy)[数组 动态规划]
- Leetcode解题笔记121. Best Time to Buy and Sell Stock [Easy] 动态规划
- 动态规划-121. Best Time to Buy and Sell Stock
- 121. Best Time to Buy and Sell Stock 类别:动态规划 难度:easy
- 动态规划——121. Best Time to Buy and Sell Stock[easy]
- 123.leetcode Best Time to Buy and Sell Stock III(hard)[动态规划算法 数组]
- 【动态规划】Leetcode编程题解:121. Best Time to Buy and Sell Stock Add to List
- 【Leetcode-Easy-121】Best Time to Buy and Sell Stock
- 【Leetcode】121. Best Time to Buy and Sell Stock 【动态规划】
- ※ Leetcode - Dynamic Programming - 121. Best Time to Buy and Sell Stock(动态规划)
- 动态规划入门级教学(leetcode)121.Best Time to Buy and Sell Stock
- Leetcode(W8):121. Best Time to Buy and Sell Stock(动态规划)
- 【动态规划】Best Time to Buy and Sell Stock IV
- Best Time to Buy and Sell Stock IV(动态规划)
- 121. Best Time to Buy and Sell Stock [easy] (Python)
- 121. Best Time to Buy and Sell Stock -Easy
- leetcode---best-time-to-buy-and-sell-stock---数组
- LeetCode动态规划思想:Best Time to Buy and Sell Stock III
- C# Timer类详解
- Swift学习笔记(二)
- hive join详解
- android5.1 PowerManagerService和DisplayPowerControler、DisplayPowerState关系
- 那些著名或非著名的iOS面试题(上)
- 121.LeetCode Best Time to Buy and Sell Stock(easy)[数组 动态规划]
- Android Studio系列教程二--基本设置与运行
- Web体系结构
- 亿级Web系统搭建——单机到分布式集群
- C# 单例模式的不同写法对静态变量的影响
- Android中Bitmap, Drawable, Byte,ID之间的转化
- 15电气郄慧敏vb作业计算一位数乘以一位数
- 一位数乘以一位数
- 9个循环3