Best Time to Buy and Sell Stock(LeetCode)
来源:互联网 发布:手机淘宝店铺链接在哪? 编辑:程序博客网 时间:2024/05/23 21:39
题目:
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.
题目分析:
题目给出一个数组,每个数代表一天股票的价格。总共只能进行一笔交易(一买一卖)。问最多能挣多少钱?
思路:
暂略
注意点:
- 可以当天买进卖出,即收益为0。当其他时候收益为负,0有可能是最大收益。
- 注意,最后如果result < 0,则返回0即可
代码:
public class Solution { public int maxProfit(int[] prices) { if (prices.length == 0){//to judge an array is empty or not, cannot use "prices == null", but should use "prices.length == 0" return 0; } int result = prices[prices.length - 1] - prices[0]; int begin = 0; while (begin < prices.length){ int minIndex = begin, maxIndex = prices.length - 1; for (int i = prices.length - 1; i > minIndex; i--){ if (prices[i] > prices[maxIndex]){ maxIndex = i; } } for (int i = begin; i < maxIndex; i++){ if (prices[i] < prices[minIndex]){ minIndex = i; } } int profit = prices[maxIndex] - prices[minIndex]; if (profit > result){ result = profit; } begin = maxIndex + 1; } if (result < 0){ return 0; } return result; }}
0 0
- 【LeetCode】Best Time to Buy and Sell Stock & Best Time to Buy and Sell Stock
- [LeetCode] [LeetCode]Best Time to Buy and Sell Stock
- 【LeetCode with Python】 Best Time to Buy and Sell Stock
- [LeetCode]Best Time to Buy and Sell Stock
- [LeetCode]Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock
- LeetCode Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock III
- Leetcode: Best time to buy and sell a stock I
- Leetcode: Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock III
- [Leetcode] Best Time to Buy and Sell Stock
- [Leetcode] Best Time to Buy and Sell Stock II
- [Leetcode] Best Time to Buy and Sell Stock III
- LeetCode : Best Time to Buy and Sell Stock II
- [leetcode] Best Time to Buy and Sell Stock
- leetcode 16: Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock
- C++小知识之指针和引用的区别
- 黑马程序员 java学习笔记——IO流1
- typedef用法
- Kettle 4.2源码分析第三讲--Kettle 转换机制transformation介绍
- 类的单例模式
- Best Time to Buy and Sell Stock(LeetCode)
- 【二维dp_右下递推】interleaving、Distinct Subsequences、字符串交错、min edit distance、longest common sequence(LCS)
- Ugly Numbers(poj 1338)
- JDOM java操作XML
- php学习笔记 1
- 消息
- 随笔-清明那些事
- C++临时对象减少的方法
- C++用new和不用new创建类对象区别