public class Solution {
public int MaxProfit(int[] prices)
{
//寻找最优极值点(包括2个端点) if (prices.Length < )
{
return ;
}
else if (prices.Length == )
{
return prices[] - prices[] > ? prices[] - prices[] : ;
}
else//至少3个点
{
//先对原始数据进行压缩
var list = new List<int>();
for (int i = ; i < prices.Length - ; i++)
{
if (prices[i] != prices[i + ])
{
list.Add(prices[i]);
}
}
var last = list.LastOrDefault();
if (last != prices[prices.Length - ])
{
list.Add(prices[prices.Length - ]);
} var dic = new Dictionary<int, int>();//记录所有极值点极其类型
//Key是index,Value是类型:-1是极小,1是极大 //list已经压缩,没有平行点了
for (int i = ; i < list.Count - ; i++)
{
//判断是否是极大值点
if (list[i - ] < list[i] && list[i] > list[i + ])
{
dic.Add(i, );
}
else if (list[i - ] > list[i] && list[i] < list[i + ])
{
dic.Add(i, -);
}
//判断是否是极小值点
} //处理端点
if (dic.Count == )
{
return list[list.Count - ] - list[] > ? list[list.Count - ] - list[] : ;
}
else
{
var list2 = dic.OrderBy(x => x.Key).ToList();
var d1 = list2.FirstOrDefault();
var d2 = list2.LastOrDefault();
if (d1.Value == )
{
list2.Add(new KeyValuePair<int, int>(, -));
}
else
{
list2.Add(new KeyValuePair<int, int>(, ));
} if (d2.Value == )
{
list2.Add(new KeyValuePair<int, int>(list.Count - , -));
}
else
{
list2.Add(new KeyValuePair<int, int>(list.Count - , ));
} list2 = list2.OrderBy(x => x.Key).ToList();//得到全部的极值点 var maxProfit = ; for (int i = ; i < list2.Count; i++)
{
if (list2[i].Value == -)
{
for (int j = i; j < list2.Count; j++)
{
if (list2[j].Value == )
{
if (list[list2[j].Key] - list[list2[i].Key] > maxProfit)
{
maxProfit = list[list2[j].Key] - list[list2[i].Key];
}
}
}
}
}
return maxProfit;
} }
}
}

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/#/description

原来的计算方式太复杂了,使用优化的方式如下:

class Solution {
public:
int maxProfit(vector<int>& prices) {
int minprice = INT_MAX;
int maxprofit = ;
for (int i = ; i < prices.size(); i++)
{
if (minprice > prices[i])
{
minprice = prices[i];
}
else if (prices[i] - minprice > maxprofit)
{
maxprofit = prices[i] - minprice;
}
}
return maxprofit;
}
};

补充一个python的实现:

 import sys
class Solution:
def maxProfit(self, prices: List[int]) -> int:
n = len(prices)
maxval =
minval = sys.maxsize
for i in range(n):
cur = prices[i]
minval = min(minval,cur)
maxval = max(maxval,cur-minval)
return maxval

leetcode121的更多相关文章

  1. LeetCode121:Best Time to Buy and Sell Stock

    题目: Say you have an array for which the ith element is the price of a given stock on day i. If you w ...

  2. Leetcode-121 Best Time to Buy and Sell Stock

    #121   Best Time to Buy and Sell Stock Say you have an array for which the ith element is the price ...

  3. [Swift]LeetCode121. 买卖股票的最佳时机 I | Best Time to Buy and Sell Stock

    Say you have an array for which the ith element is the price of a given stock on day i. If you were ...

  4. LeetCode121.买卖股票的最佳时机

    给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格. 如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润. 注意你不能在买入股票前卖出股票. 示例 ...

  5. [leetcode121]股票买卖 Best Time to Buy and Sell Kadane算法

    [题目] Say you have an array for which the ith element is the price of a given stock on day i. If you ...

  6. leetcode121—Best Time to Buy and Sell Stock

    Say you have an array for which the ith element is the price of a given stock on day i. If you were ...

  7. leetcode 买卖股票问题

    leetcode121 Best Time to Buy and Sell Stock 说白了找到最大的两组数之差即可 class Solution { public: int maxProfit(v ...

  8. LeetCode-714.Best Time to Buy and Sell Stock with Transaction Fee

    Your are given an array of integers prices, for which the i-th element is the price of a given stock ...

  9. LeetCode-188.Best Time to Buy and Sell Stock IV

    Say you have an array for which the ith element is the price of a given stock on day i. Design an al ...

随机推荐

  1. vue学习笔记 - 篇2

    1.借助Vue.extend()方法创建组件 注意点 var Aaa = Vue.extend({ template: "<h1>这是标题</h1>" }) ...

  2. 通过pid杀死进程

    bool ****::KillProcess(DWORD pid) { // When the all operation fail this function terminate the " ...

  3. asp.net mvc6+ef框架做的书籍管理项目

    效果图: 目录结构: book控制器代码: using System; using System.Collections.Generic; using System.Linq; using Syste ...

  4. SpringBoot(三)thymeleaf+JPA+MySql

    接着上一节的 第一步:在pom文件中加入以下代码: <!--JPA--> <dependency> <groupId>org.springframework.boo ...

  5. UA池和代理池

    scrapy下载中间件 UA池 代理池 一.下载中间件 先祭出框架图: 下载中间件(Downloader Middlewares) 位于scrapy引擎和下载器之间的一层组件. - 作用: (1)引擎 ...

  6. 解决eclipse高版本JDK编译的项目到低版本JDK服务器上不能运行的问题

    错误提示信息:Unsupported major.minor version 52.0,意思是说,当前jdk的版本不支持更高版本jdk编译出来的class文件. 我的编译环境,eclipse使用的是j ...

  7. 我的代码-models

    # coding: utf-8 # In[1]: import pandas as pdimport numpy as npfrom sklearn import treefrom sklearn.s ...

  8. struct 和typedef struct

    1.typedef (1)typedef的使用 定义一种类型的别名,而不只是简单的宏替换(见陷阱一).用作同时声明指针型的多个对象 typedef char* PCHAR; // 一般用大写,为cha ...

  9. 【SpringBoot】数据库操作之整合Mybaties和事务讲解

    ========================8.数据库操作之整合Mybaties和事务讲解 ================================ 1.SpringBoot2.x持久化数 ...

  10. PythonStudy——逻辑运算符 Logical Operators

    在Python中,None.任何数值类型中的0.空字符串“”.空元组().空列表[].空字典{}都被当作False,还有自定义类型,如果实现了 __ nonzero __ () 或 __ len __ ...