zoukankan      html  css  js  c++  java
  • leetcode 122. Best Time to Buy and Sell Stock II ----- java

    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 (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).

    可以多次买入卖出,求出最大利润。

    由于可以多次买入卖出,所以每次遇到有利润都可以卖出,所以一直循环然后能交易就交易就可以了。

    public class Solution {
        public int maxProfit(int[] prices) {
            int len = prices.length;
            if( len < 2)
                return 0;
            int result = 0;
            int start = 0;
            while( start < len ){
                start = getStart(prices,start);
                if( start == len-1)
                    break;
                result+=(prices[start+1]-prices[start]);
                start++;
            }
            return result;
        }
    
        public int getStart(int[] prices,int start){
            int buy = prices[start];
            while( start < prices.length ){
                if( buy >= prices[start]){
                    buy = prices[start];
                    start++;
                }else
                    break;
            }
            return start-1;
            
        }
    }
  • 相关阅读:
    百万级数据库优化方案
    MySQL架构及优化原理
    性能优化建议
    索引
    sql语句优化(持续更新)
    sql语句优化原理
    常用命令
    常见问题
    三、范围和生命周期
    【UVa】[11582]Colossal Fibonacci Numbers!
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/6023790.html
Copyright © 2011-2022 走看看