zoukankan      html  css  js  c++  java
  • 121. Best Time to Buy and Sell Stock买卖股票12

    [抄题]:

    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.

    Input: [7, 1, 5, 3, 6, 4]
    Output: 5
    
    max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

    [一句话思路]:贪心算法。不要用数组i,j角标,直接用min, profit表示价格,更方便。

    [画图]:

    [一刷]:

    min, profit都记得要初始化

    [总结]:

    [复杂度]:

    n/1

    [英文数据结构]:

    Range Queries

    [其他解法]:

    [题目变变变]:

    maximum subarray最大求和子数组

    class Solution {
        public int maxProfit(int[] prices) {
            if (prices.length == 0 || prices == null) {
                return 0;
            }
            
            int min = Integer.MAX_VALUE;
            int profit = 0;
            for (int i = 0; i < prices.length; i++) {
                min = min < prices[i] ? min : prices[i];
                profit = (prices[i] - min) > profit ? prices[i] - min : profit;
            }
            
            return profit;
        }
    }
    View Code

    [抄题]:

    Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).可以买卖无数次,但是必须先卖后买。

    [一句话思路]:

    股票profit或者数组sum只有一个时,用贪心算法,容易定义。

    股票profit是很多利润的累加时,用数组i,j角标来叠加。因为只要上涨就要卖出,攫取利润。

    [画图]:

    [一刷]:

    由于出现了prices[i + 1], 循环体的上界要减1,为for (int i = 0; i < prices.length - 1; i++) 

    [总结]:

    [复杂度]:

    [英文数据结构]:

    [其他解法]:

    [题目变变变]:

    class Solution {
        public int maxProfit(int[] prices) {
            if (prices.length == 0 || prices == null) {
                return 0;
            }
            
            int diff = 0;
            for (int i = 0; i < prices.length - 1; i++) {
                if (prices[i + 1] - prices[i] > 0) {
                    diff += prices[i + 1] - prices[i];
                }
            }
            
            return diff;
        }
    }
    View Code
  • 相关阅读:
    ASP.NET Core 中的管道机制
    常见的 HttpModule
    IIS+Asp.Net Mvc必须知道的事(解决启动/重启/自动回收站点后第一次访问慢问题)
    ASP.NET三剑客 HttpApplication HttpModule HttpHandler 解析
    Js国际化
    MethodImplOptions
    Java守护线程普通线程的例子
    Java启动新线程的几种方式(Runnable、Callable、CompletableFuture)
    Tomcat源码分析(3)-容器Container整体架构
    Tomcat源码分析(2)-连接器Connector整体架构
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8017175.html
Copyright © 2011-2022 走看看