leetcode-121-买卖股票的最佳时机
2019-07-30 10:19
190 查看
问题:
可以将问题转化为如下图所示,即求多个累计的收入差
分析:
如果当前位置i的价格比i+1的价格高,则当前不是买入点,则继续判断下一个位置,
如果当前位置i的价格比i+1的价格低,并且i+1仍比i+1+1低,则在当前位置买入,知道i+n比i+n+1大时,卖出。
继续下一轮判断
package com.example.demo; public class Test121 { /** * 多个 * * @param prices * @return */ public int maxProfit(int[] prices) { if (prices == null || prices.length == 0) { return 0; } int cur = 0; int vally = prices[0]; int peak = 0; int income = 0; while (cur < prices.length - 1) { //找到卖出点,谷底 while (cur < prices.length - 1 && prices[cur] >= prices[cur + 1]) { cur++; } vally = prices[cur]; //找到比当前大的值(即最高点,顶峰) while (cur < prices.length - 1 && prices[cur] <= prices[cur + 1]) { cur++; } peak = prices[cur]; income += peak - vally; //如果此时cur仍然没有到最后,则进行再一次循环 } return income; } public static void main(String[] args) { Test121 t = new Test121(); int[] arr = {7, 1, 5, 3, 6, 4}; int i = t.maxProfit(arr); System.out.println(i); } }
相关文章推荐
- LeetCode题库解答与分析——#121. 买卖股票的最佳时机BestTimeToBuyAndSellStock
- LeetCode 121 买卖股票的最佳时机 Python
- C++Leetcode121:买卖股票的最佳时机
- LeetCode刷题笔记121:买卖股票的最佳时机
- LeetCode-121.买卖股票的最佳时机(相关话题:动态规划)
- Leetcode121: 买卖股票的最佳时机
- 基础算法之买卖股票最佳时机(Leetcode-121)
- Leetcode121 Best Time to Buy and Sell Stock(买卖股票的最佳时机1)
- leetcode-买卖股票的最佳时机④*
- LeetCode:买卖股票的最佳时机 II(Python版本)
- leetcode 121.Best Time to Buy and Sell Stock 股票买卖最佳时间
- Java&LeetCode 初入门——122. 买卖股票的最佳时机 II
- [Leetcode] Best time to buy and sell stock 买卖股票的最佳时机
- LeetCode 122 买卖股票的最佳时机2 Python
- LeetCode_Q122_买卖股票的最佳时机 II
- LeetCode刷题:买卖股票的最佳时机(day16)
- 121. 买卖股票的最佳时机
- leetCode-122.买卖股票的最佳时机Ⅱ
- [Java语言] [Leetcode] Best Time to Buy and Sell Stock 买卖股票的最佳时机
- LeetCode——121. 买卖股票的最佳时机