zoukankan      html  css  js  c++  java
  • 【LEETCODE】37、122题,Best Time to Buy and Sell Stock II

    package y2019.Algorithm.array;
    
    /**
     * @ProjectName: cutter-point
     * @Package: y2019.Algorithm.array
     * @ClassName: MaxProfit2
     * @Author: xiaof
     * @Description: 122. Best Time to Buy and Sell Stock II
     * Say you have an array for which the ith element is the price of a given stock on day i.
     * Design an algorithm to find the maximum profit. You may complete as many transactions as you like
     * (i.e., buy one and sell one share of the stock multiple times).
     *
     * Input: [7,1,5,3,6,4]
     * Output: 7
     * Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
     *              Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
     *
     * 你可以尽可能多的进行交易
     * 那么这个题就是有的赚就买的意思了
     *
     * @Date: 2019/7/2 10:12
     * @Version: 1.0
     */
    public class MaxProfit2 {
    
        public int solution(int[] prices) {
            //那就是贪心算法了
            Integer curSmall = 0, result = 0;
            if(prices.length == 0)
                return 0; //没得赚
            else {
                curSmall = prices[0];
            }
    
            for(int i = 1; i < prices.length; ++i) {
                int temp = prices[i];
    
                if(curSmall == null || temp < curSmall) {
                    curSmall = temp;
                } else if(temp > curSmall) {
                    result += temp - curSmall;
                    curSmall = temp;
                }
            }
    
            return result;
        }
    
        public static void main(String args[]) {
    
            int pres[] = {1,2,3,4,5};
            System.out.println(new MaxProfit2().solution(pres));
    
        }
    
    }

  • 相关阅读:
    vue day6 分页显示
    vue day5 分页控件
    vue day4 table
    c# excel xlsx 保存
    diff算法
    Web Workers
    多线程
    Http请求优化
    高效编写代码
    渲染引擎
  • 原文地址:https://www.cnblogs.com/cutter-point/p/11119427.html
Copyright © 2011-2022 走看看